target
stringlengths
5
300
feat_repo_name
stringlengths
6
76
text
stringlengths
26
1.05M
src/server.js
Calvin-Huang/LiveAPIExplore-Server
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import 'babel-polyfill'; import http from 'http'; import path from 'path'; import express from 'express'; import xhub from 'express-x-hub'; import cookieParser from 'cookie-parser'; import bodyParser from 'body-parser'; import expressJwt from 'express-jwt'; import expressGraphQL from 'express-graphql'; import jwt from 'jsonwebtoken'; import { createClient } from 'redis'; import React from 'react'; import ReactDOM from 'react-dom/server'; import { Provider } from 'react-redux'; import { applyRouterMiddleware, Router, BrowserHistory, match, RouterContext } from 'react-router'; import useScroll from 'react-router-scroll'; import Helmet from 'react-helmet'; import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import PrettyError from 'pretty-error'; import App from './components/App'; import Html from './components/Html'; import { ErrorPageWithoutStyle } from './routes/error/ErrorPage'; import errorPageStyle from './routes/error/ErrorPage.css'; import passport from './core/passport'; import models from './data/models'; import schema from './data/schema'; import routes from './routes'; import reducers from './reducers'; import { port, auth, redisUrl } from './config'; import io from './socket'; import util from 'util'; const app = express(); // // Tell any CSS tooling (such as Material UI) to use all vendor prefixes if the // user agent is not known. // ----------------------------------------------------------------------------- global.navigator = global.navigator || {}; global.navigator.userAgent = global.navigator.userAgent || 'all'; // // Register Node.js middleware // ----------------------------------------------------------------------------- app.use(express.static(path.join(__dirname, 'public'))); app.use(cookieParser()); app.use(xhub({ algorithm: 'sha1', secret: process.env.APP_SECRET })); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); // // Authentication // ----------------------------------------------------------------------------- app.use( expressJwt({ secret: auth.jwt.secret, credentialsRequired: false, getToken: function fromHeaderOrQuertstring(req) { if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') { return req.headers.authorization.split(' ')[1]; } else if (req.query && req.query.token) { return req.query.token; } return null; }, }), (req, res, next) => { const allowedPaths = ['/login', '/graphql', '/auth/facebook', '/auth/facebook/callback', '/fb-subscribe']; if (allowedPaths.indexOf(req.path) > -1) { return next(); } if (!req.user) { return res.sendStatus(401); } const adminAllowedPaths = ['/', '/users', '/admins']; if (adminAllowedPaths.indexOf(req.path) > -1) { if (!req.user.admin) { return res.sendStatus(401); } } return next(); }, ); app.use(passport.initialize()); app.get('/auth/facebook', passport.authenticate('facebook', { scope: ['email', 'manage_pages', 'publish_pages'], session: false }), ); app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/?failed=true', session: false }), (req, res) => { const expiresIn = 60 * 60 * 24 * 180; // 180 days const token = jwt.sign(req.user, auth.jwt.secret, { expiresIn }); res.cookie('id_token', token, { maxAge: 1000 * expiresIn, httpOnly: true }); res.redirect('/login'); }, ); // Verify with FB console. app.get('/fb-subscribe', (req, res, next) => { if (req.param('hub.mode') == 'subscribe' && req.param('hub.verify_token') == process.env.VERIFY_TOKEN) { res.send(req.param('hub.challenge')); } else { res.sendStatus(400); } }); // Subscriber for receiving FB notification. app.post('/fb-subscribe', // Middleware for authorization. (req, res, next) => { if (req.isXHub && req.isXHubValid()) { return next(); } else { res.sendStatus(401); } }, (req, res) => { const { entry, object } = req.body; if (object === 'page') { entry.forEach((eachEntry) => { const { changes } = eachEntry; changes.forEach((change) => { console.log(util.inspect(change)); const { field, value: { sender_name, sender_id, item, post_id, verb, message } } = change; // Handle feed if (field === 'feed') { // Add new comment into redis and broadcast to subscribers. if (item === 'comment' && verb === 'add') { const videoId = post_id.split('_')[1]; const redis = createClient(redisUrl); redis.rpush(`live:${videoId}:comments`, message); redis.publish(`live:${videoId}:comments:latest`, message); redis.quit(); } } }); }); } res.send('OK'); } ); // // Register API middleware // ----------------------------------------------------------------------------- app.use('/graphql', expressGraphQL(req => ({ schema, graphiql: process.env.NODE_ENV !== 'production', rootValue: { request: req }, pretty: process.env.NODE_ENV !== 'production', }))); // // Register server-side rendering middleware // ----------------------------------------------------------------------------- app.get('*', async (req, res, next) => { try { const css = new Set(); // const route = await UniversalRouter.resolve(routes, { // path: req.path, // query: req.query, // }); // if (route.redirect) { // res.redirect(route.status || 302, route.redirect); // return; // } match({ routes, location: req.url }, (error, redirectLocation, renderProps) => { if (error) { res.status(500).send(error.message) } else if (redirectLocation) { res.redirect(302, redirectLocation.pathname + redirectLocation.search) } else if (renderProps) { const store = createStore(reducers, applyMiddleware(thunk)); const htmlChildren = ReactDOM.renderToString( <Provider store={store}> <RouterContext {...renderProps} /> </Provider> ); const html = ReactDOM.renderToStaticMarkup(<Html children={htmlChildren} />); res.status(200).send(`<!doctype html>${html}`); } else { res.status(404).send('Not found') } }); // res.status(route.status || 200); // res.send(`<!doctype html>${html}`); } catch (err) { next(err); } }); // // Error handling // ----------------------------------------------------------------------------- const pe = new PrettyError(); pe.skipNodeFiles(); pe.skipPackage('express'); app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars console.log(pe.render(err)); // eslint-disable-line no-console const html = ReactDOM.renderToStaticMarkup( <Html title="Internal Server Error" description={err.message} > {ReactDOM.renderToString(<ErrorPageWithoutStyle error={err} />)} </Html>, ); res.status(err.status || 500); res.send(`<!doctype html>${html}`); }); // // Launch the server // ----------------------------------------------------------------------------- /* eslint-disable no-console */ const server = http.createServer(app); io.attach(server); models.sync().catch(err => console.error(err.stack)).then(() => { server.listen(port, () => { console.log(`The server is running at http://localhost:${port}/`); }); }); /* eslint-enable no-console */
packages/material-ui-icons/src/Exposure.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M15 17v2h2v-2h2v-2h-2v-2h-2v2h-2v2h2zm5-15H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM5 5h6v2H5V5zm15 15H4L20 4v16z" /></g> , 'Exposure');
ajax/libs/flocks.js/0.15.0/flocks.js
freak3dot/cdnjs
/** @jsx React.DOM */ /* jshint node: true, browser: true, newcap: false */ /** * The Flocks library module. * * @module Flocks * @main Flocks */ // if it's in a <script> it's defined already // otherwise assume commonjs if (typeof React === 'undefined') { var React = require('react'); } // wrap the remainder (function() { 'use strict'; var initialized = false, updateBlocks = 0, dirty = false, tagtype = undefined, handler = function(Ignored) { return true; }, finalizer = function() { return true; }, prevFCtx = {}, nextFCtx = {}, flocks2_ctxs = { flocks2context: React.PropTypes.object }; function flocksLog(Level, Message) { if (typeof Level === 'string') { if (array_member(Level, ['warn','debug','error','log','info','exception','assert'])) { console[Level]('Flocks2 [' + Level + '] ' + Message.toString()); } else { console.log('Flocks2 [Unknown level] ' + Message.toString()); } } else if (nextFCtx.flocks_config === undefined) { console.log('Flocks2 pre-config [' + Level.toString() + '] ' + Message.toString()); } else if (nextFCtx.flocks_config.log_level >= Level) { console.log('Flocks2 [' + Level.toString() + '] ' + Message.toString()); } } function enforceString(On, Label) { if (typeof On !== 'string') { throw Label || 'Argument must be a string'; } } function enforceArray(On, Label) { if (!isArray(On)) { throw Label || 'Argument must be an array'; } } function isArray(maybeArray) { return (Object.prototype.toString.call(maybeArray) === '[object Array]'); } function isNonArrayObject(maybeArray) { if (typeof maybeArray !== 'object') { return false; } if (Object.prototype.toString.call(maybeArray) === '[object Array]') { return false; } return true; } function setByKey(Key, MaybeValue) { enforceString(Key, "Flocks2 set/2 must take a string for its key"); nextFCtx[Key] = MaybeValue; flocksLog(1, " - Flocks2 setByKey \"" + Key + "\""); attemptUpdate(); } // function setByPath(Key, MaybeValue) { flocksLog(0, ' - Flocks2 setByPath stub' ); attemptUpdate(); } // function setByObject(Key, MaybeValue) { flocksLog(0, ' - Flocks2 setByObject stub'); attemptUpdate(); } function set(Key, MaybeValue) { flocksLog(3, ' - Flocks2 multi-set'); if (typeof Key === 'string') { setByKey(Key, MaybeValue); } // else if (isArray(Key)) { setByPath(Key, MaybeValue); } // else if (isNonArrayObject(Key)) { setByObject(Key); } else { throw 'Flocks2 set/1,2 key must be a string or an array'; } } function clone(obj) { if ((null === obj) || ('object' != typeof obj)) { return obj; } var copy = obj.constructor(); for (var attr in obj) { if (obj.hasOwnProperty(attr)) { copy[attr] = obj[attr]; } } return copy; } // ... lol function array_member(Item, Array) { return (!!(~( Array.indexOf(Item, 0) ))); } function attemptUpdate() { flocksLog(3, ' - Flocks2 attempting update'); dirty = true; if (!(initialized)) { flocksLog(1, ' x Flocks2 skipped update: root is not initialized'); return null; } if (updateBlocks) { flocksLog(1, ' x Flocks2 skipped update: lock count updateBlocks is non-zero'); return null; } /* whargarbl see issue #9 https://github.com/StoneCypher/flocks.js/issues/9 if (deepCompare(nextFCtx, prevFCtx)) { flocksLog(2, ' x Flocks2 skipped update: no update to state'); return true; } */ if (!(handler(nextFCtx))) { flocksLog(0, ' ! Flocks2 rolling back update: handler rejected propset'); nextFCtx = prevFCtx; dirty = false; return null; } prevFCtx = nextFCtx; flocksLog(3, ' - Flocks2 update passed'); React.render( React.createFactory(tagtype)( { flocks2context: nextFCtx } ), document.body ); dirty = false; flocksLog(3, ' - Flocks2 update complete; finalizing'); finalizer(); return true; } function create(iFlocksConfig, iFlocksData) { var FlocksConfig = iFlocksConfig || {}, FlocksData = iFlocksData || {}, target = FlocksConfig.target || document.body, stub = function() { window.alert('whargarbl stub'); attemptUpdate(); }, updater = { get: stub, set: set, override: stub, clear: stub, update: stub, lock: stub, unlock: stub }; FlocksConfig.log_level = FlocksConfig.log_level || -1; tagtype = FlocksConfig.control; FlocksData.flocks_config = FlocksConfig; nextFCtx = FlocksData; flocksLog(1, 'Flocks2 root creation begins'); if (!(tagtype)) { throw 'Flocks2 fatal error: must provide a control in create/2 FlocksConfig'; } if (FlocksConfig.handler) { handler = FlocksConfig.handler; flocksLog(3, ' - Flocks2 handler assigned' ); } if (FlocksConfig.finalizer) { finalizer = FlocksConfig.finalizer; flocksLog(3, ' - Flocks2 finalizer assigned'); } if (FlocksConfig.preventAutoContext) { flocksLog(2, ' - Flocks2 skipping auto-context'); } else { flocksLog(2, ' - Flocks2 engaging auto-context'); this.fctx = clone(nextFCtx); } flocksLog(3, 'Flocks2 creation finished; initializing'); initialized = true; attemptUpdate(); flocksLog(3, 'Flocks2 expose updater'); this.fupd = updater; this.fset = updater.set; flocksLog(3, 'Flocks2 initialization finished'); return updater; } var Mixin = { contextTypes : flocks2_ctxs, childContextTypes : flocks2_ctxs, componentWillMount: function() { flocksLog(1, ' - Flocks2 component will mount: ' + this.constructor.displayName); flocksLog(3, typeof this.props.flocks2context === 'undefined'? ' - No F2 Context Prop' : ' - F2 Context Prop found'); flocksLog(3, typeof this.context.flocks2context === 'undefined'? ' - No F2 Context' : ' - F2 Context found'); if (this.props.flocks2context) { this.context.flocks2context = this.props.flocks2context; } this.fset = function(X,Y) { set(X,Y); }; this.fctx = this.context.flocks2context; }, getChildContext: function() { return this.context; } }; function atLeastFlocks(OriginalList) { if (typeof OriginalList === 'undefined') { return [ Mixin ]; } if (isArray(OriginalList)) { if (array_member(Mixin, OriginalList)) { return OriginalList; } else { var NewList = clone(OriginalList); NewList.push(Mixin); return NewList; } } throw 'Original mixin list must be an array or undefined!'; } function createClass(spec) { spec.mixins = atLeastFlocks(spec.mixins); return React.createClass(spec); } var exports = { plumbing : Mixin, createClass : createClass, mount : create, clone : clone, isArray : isArray, isNonArrayObject : isNonArrayObject, enforceString : enforceString, enforceArray : enforceArray, /* enforceNonArrayObject : enforceNonArrayObject, */ atLeastFlocks : atLeastFlocks }; if (typeof module !== 'undefined') { module.exports = exports; } else { window.flocks = exports; } }());
server/sonar-web/src/main/js/apps/settings/components/DefinitionChanges.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. */ // @flow import React from 'react'; import shallowCompare from 'react-addons-shallow-compare'; import { translate } from '../../../helpers/l10n'; export default class DefinitionChanges extends React.Component { static propTypes = { onSave: React.PropTypes.func.isRequired, onCancel: React.PropTypes.func.isRequired }; shouldComponentUpdate (nextProps: {}, nextState: ?{}) { return shallowCompare(this, nextProps, nextState); } handleSaveClick (e: Object) { e.preventDefault(); e.target.blur(); this.props.onSave(); } handleCancelChange (e: Object) { e.preventDefault(); e.target.blur(); this.props.onCancel(); } render () { return ( <div className="settings-definition-changes"> <button className="js-save-changes button-success" onClick={e => this.handleSaveClick(e)}> {translate('save')} </button> <button className="js-cancel-changes big-spacer-left button-link" onClick={e => this.handleCancelChange(e)}> {translate('cancel')} </button> </div> ); } }
examples/forms-bootstrap/src/components/dialogs-update-optimistic/Hook.js
lore/lore-forms
import React from 'react'; import createReactClass from 'create-react-class'; import PropTypes from 'prop-types'; export default createReactClass({ displayName: 'Hook', propTypes: { model: PropTypes.object.isRequired }, render: function() { const { model } = this.props; return ( <div style={{ padding: '20px' }}> <button className="btn btn-primary" onClick={() => { lore.dialog.show(() => ( lore.dialogs.tweet.update(model, { blueprint: 'optimistic' }) )) }} > Open Dialog </button> </div> ); } });
src/components/app.js
hzburki/innexiv-front-end
import React, { Component } from 'react'; import { Col, Well, Panel } from 'react-bootstrap'; import { Route, Switch } from 'react-router-dom'; import NavbarComponent from './NavbarComponent'; import SideNavComponent from './SideNavComponent'; import HomeComponent from './pages/HomeComponent'; import DeviceComponent from './pages/DeviceComponent'; import TransformationComponent from './pages/TransformationComponent'; import GraphComponent from './pages/GraphComponent'; class App extends Component { render() { return ( <div> <div className="header"> <NavbarComponent /> </div> <div className="body"> <Col md={3}> <Well> <SideNavComponent /> </Well> </Col> <Col md={9}> <Panel> <Switch> <Route path="/device/:id" component={DeviceComponent} /> <Route path="/transform/:id" component={TransformationComponent} /> <Route path="/graph/:id" component={GraphComponent} /> <Route exact path="/" component={HomeComponent} /> </Switch> </Panel> </Col> </div> <div className="footer" /> </div> ); } } export default App;
gulpfile.js
elaatifi/Winterfell
var gulp = require('gulp'); var browserify = require('browserify'); var source = require('vinyl-source-stream'); var reactify = require('reactify'); var buffer = require('vinyl-buffer'); var uglify = require('gulp-uglify'); /** * Examples Build */ gulp.task('build-examples', function() { return browserify({ debug : process.env.NODE_ENV != 'production', entries : [ 'examples/app.js' ] }) .transform(reactify, { es6 : true }) .bundle() .pipe(source('app.js')) .pipe(buffer()) .pipe(uglify()) .pipe(gulp.dest('examples/build')); }); gulp.task('watch-examples', function() { return gulp.watch([ 'src/**/*.js', 'examples/**/*.js', '!examples/build/app.js' ], {}, function() { return gulp.start('build-examples'); }); }); /** * Dev Build */ gulp.task('build-dev', function() { return browserify({ debug : process.env.NODE_ENV != 'production', entries : [ 'dev/test.js' ] }) .transform(reactify, { es6 : true }) .bundle() .pipe(source('app.js')) .pipe(buffer()) .pipe(gulp.dest('dev/build')); }); gulp.task('watch-dev', function() { return gulp.watch([ 'src/**/*.js', 'dev/**/*.js', '!dev/build/app.js' ], {}, function() { return gulp.start('build-dev'); }); });
ajax/libs/react-motion-ui-pack/0.2.5/react-motion-ui-pack.js
honestree/cdnjs
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("React"), require("ReactMotion"), require("Measure")); else if(typeof define === 'function' && define.amd) define(["React", "ReactMotion", "Measure"], factory); else if(typeof exports === 'object') exports["Transition"] = factory(require("React"), require("ReactMotion"), require("Measure")); else root["Transition"] = factory(root["React"], root["ReactMotion"], root["Measure"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_2__, __WEBPACK_EXTERNAL_MODULE_3__, __WEBPACK_EXTERNAL_MODULE_4__) { 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 = "dist/"; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _Transition = __webpack_require__(1); var _Transition2 = _interopRequireDefault(_Transition); exports['default'] = _Transition2['default']; module.exports = exports['default']; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _reactMotion = __webpack_require__(3); var _reactMeasure = __webpack_require__(4); var _reactMeasure2 = _interopRequireDefault(_reactMeasure); var _configToStyle = __webpack_require__(5); var _configToStyle2 = _interopRequireDefault(_configToStyle); var Transition = (function (_Component) { _inherits(Transition, _Component); function Transition() { var _this = this; _classCallCheck(this, Transition); _get(Object.getPrototypeOf(Transition.prototype), 'constructor', this).apply(this, arguments); this._cachedDimensions = {}; this._forceUpdate = function () { _this.forceUpdate(); }; this._getDefaultValues = function () { var _props = _this.props; var children = _props.children; var appear = _props.appear; var enter = _props.enter; var leave = _props.leave; var styles = enter; var configs = {}; if (appear) { styles = typeof appear === 'object' ? appear : leave; } _react.Children.forEach(children, function (child) { if (!child) return; configs[child.key] = { component: child, styles: styles }; }); return configs; }; this._getEndValues = function (s) { var _props2 = _this.props; var children = _props2.children; var enter = _props2.enter; var configs = {}; _react.Children.forEach(children, function (child) { if (!child) return; var dimensions = _this._cachedDimensions[child.key]; var styles = _extends({}, enter); if (styles.height && enter.height.val === 'auto') { styles.height = { val: dimensions && dimensions.height || 0 }; } if (styles.width && enter.width.val === 'auto') { styles.width = { val: dimensions && dimensions.width || 0 }; } configs[child.key] = { component: child, styles: styles }; }); return configs; }; this._willEnter = function (key, value, endValue, currentValue, currentSpeed) { var _props3 = _this.props; var appear = _props3.appear; var leave = _props3.leave; var styles = typeof appear === 'object' ? appear : leave; return _extends({}, value, { styles: styles }); }; this._willLeave = function (key, value, endValue, currentValue, currentSpeed) { return _extends({}, value, { styles: _this.props.leave }); }; this._childrenToRender = function (currValues) { return Object.keys(currValues).map(function (key) { var currValue = currValues[key]; var component = currValue.component; var styles = currValue.styles; return( // measure child and force update to run // react motion again once we have dimensions _react2['default'].createElement( _reactMeasure2['default'], { key: key, onChange: _this._forceUpdate }, function (dimensions) { _this._cachedDimensions[key] = dimensions; return (0, _react.cloneElement)(component, { style: (0, _configToStyle2['default'])(styles), dimensions: dimensions }); } ) ); }); }; } _createClass(Transition, [{ key: 'render', value: function render() { var _this2 = this; var _props4 = this.props; var component = _props4.component; var onlyChild = _props4.onlyChild; var appear = _props4.appear; return _react2['default'].createElement( _reactMotion.TransitionSpring, { defaultValue: this._getDefaultValues(), endValue: this._getEndValues(), willEnter: this._willEnter, willLeave: this._willLeave }, function (currValues) { var children = _this2._childrenToRender(currValues); var wrapper = undefined; if (onlyChild) { if (children.length === 1) { wrapper = _react.Children.only(children[0]); } else { wrapper = (0, _react.createElement)(component, { style: { display: 'none' } }); } } else { wrapper = (0, _react.createElement)(component, _this2.props, children); } return wrapper; } ); } }], [{ key: 'propTypes', value: { component: _react.PropTypes.string, onlyChild: _react.PropTypes.bool, appear: _react.PropTypes.oneOfType([_react.PropTypes.bool, _react.PropTypes.object]), enter: _react.PropTypes.object, leave: _react.PropTypes.object }, enumerable: true }, { key: 'defaultProps', value: { component: 'div', // define the wrapping tag around the elements you want to transition in/out onlyChild: false, // useful if you only want to transition in/out 1 element rather than a list appear: true, // accepts an object or boolean, if boolean passed it will use "leave" as the origin point of the transition enter: { opacity: { val: 1 } }, leave: { opacity: { val: 0 } } }, enumerable: true }]); return Transition; })(_react.Component); exports['default'] = Transition; module.exports = exports['default']; /***/ }, /* 2 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_2__; /***/ }, /* 3 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_3__; /***/ }, /* 4 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_4__; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var transform = __webpack_require__(6)('transform'); var UNIT_TRANSFORMS = ['translateX', 'translateY', 'translateZ', 'transformPerspective']; var DEGREE_TRANFORMS = ['rotate', 'rotateX', 'rotateY', 'rotateZ', 'skewX', 'skewY', 'scaleZ']; var UNITLESS_TRANSFORMS = ['scale', 'scaleX', 'scaleY']; var TRANSFORMS = UNIT_TRANSFORMS.concat(DEGREE_TRANFORMS, UNITLESS_TRANSFORMS); exports['default'] = function (configs) { var styles = {}; Object.keys(configs).map(function (key) { var isTransform = TRANSFORMS.indexOf(key) > -1; var value = configs[key].val; if (isTransform) { var transformProps = styles[transform] || ''; if (UNIT_TRANSFORMS.indexOf(key) > -1) { transformProps += key + '(' + value + 'px) '; } else if (DEGREE_TRANFORMS.indexOf(key) > -1) { transformProps += key + '(' + value + 'deg) '; } else if (UNITLESS_TRANSFORMS.indexOf(key) > -1) { transformProps += key + '(' + value + ') '; } styles[transform] = transformProps; } else { styles[key] = value; } }); return styles; }; module.exports = exports['default']; /***/ }, /* 6 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = getVendorPrefix; function getVendorPrefix(prop) { var styles = document.createElement('p').style; var vendors = ['ms', 'O', 'Moz', 'Webkit']; if (styles[prop] === '') return prop; prop = prop.charAt(0).toUpperCase() + prop.slice(1); for (var i = vendors.length; i--;) { if (styles[vendors[i] + prop] === '') { return vendors[i] + prop; } } } module.exports = exports['default']; /***/ } /******/ ]) }); ;
node_modules/es6-module-loader/node_modules/babel-core/node_modules/core-js/index.js
ksomville/Angular2-Hearthstone
/** * Core.js 0.6.1 * https://github.com/zloirock/core-js * License: http://rock.mit-license.org * © 2015 Denis Pushkarev */ !function(global, framework, undefined){ 'use strict'; /****************************************************************************** * Module : common * ******************************************************************************/ // Shortcuts for [[Class]] & property names var OBJECT = 'Object' , FUNCTION = 'Function' , ARRAY = 'Array' , STRING = 'String' , NUMBER = 'Number' , REGEXP = 'RegExp' , DATE = 'Date' , MAP = 'Map' , SET = 'Set' , WEAKMAP = 'WeakMap' , WEAKSET = 'WeakSet' , SYMBOL = 'Symbol' , PROMISE = 'Promise' , MATH = 'Math' , ARGUMENTS = 'Arguments' , PROTOTYPE = 'prototype' , CONSTRUCTOR = 'constructor' , TO_STRING = 'toString' , TO_STRING_TAG = TO_STRING + 'Tag' , TO_LOCALE = 'toLocaleString' , HAS_OWN = 'hasOwnProperty' , FOR_EACH = 'forEach' , ITERATOR = 'iterator' , FF_ITERATOR = '@@' + ITERATOR , PROCESS = 'process' , CREATE_ELEMENT = 'createElement' // Aliases global objects and prototypes , Function = global[FUNCTION] , Object = global[OBJECT] , Array = global[ARRAY] , String = global[STRING] , Number = global[NUMBER] , RegExp = global[REGEXP] , Date = global[DATE] , Map = global[MAP] , Set = global[SET] , WeakMap = global[WEAKMAP] , WeakSet = global[WEAKSET] , Symbol = global[SYMBOL] , Math = global[MATH] , TypeError = global.TypeError , RangeError = global.RangeError , setTimeout = global.setTimeout , setImmediate = global.setImmediate , clearImmediate = global.clearImmediate , parseInt = global.parseInt , isFinite = global.isFinite , process = global[PROCESS] , nextTick = process && process.nextTick , document = global.document , html = document && document.documentElement , navigator = global.navigator , define = global.define , console = global.console || {} , ArrayProto = Array[PROTOTYPE] , ObjectProto = Object[PROTOTYPE] , FunctionProto = Function[PROTOTYPE] , Infinity = 1 / 0 , DOT = '.'; // http://jsperf.com/core-js-isobject function isObject(it){ return it !== null && (typeof it == 'object' || typeof it == 'function'); } function isFunction(it){ return typeof it == 'function'; } // Native function? var isNative = ctx(/./.test, /\[native code\]\s*\}\s*$/, 1); // Object internal [[Class]] or toStringTag // http://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring var toString = ObjectProto[TO_STRING]; function setToStringTag(it, tag, stat){ if(it && !has(it = stat ? it : it[PROTOTYPE], SYMBOL_TAG))hidden(it, SYMBOL_TAG, tag); } function cof(it){ return toString.call(it).slice(8, -1); } function classof(it){ var O, T; return it == undefined ? it === undefined ? 'Undefined' : 'Null' : typeof (T = (O = Object(it))[SYMBOL_TAG]) == 'string' ? T : cof(O); } // Function var call = FunctionProto.call , apply = FunctionProto.apply , REFERENCE_GET; // Partial apply function part(/* ...args */){ var fn = assertFunction(this) , length = arguments.length , args = Array(length) , i = 0 , _ = path._ , holder = false; while(length > i)if((args[i] = arguments[i++]) === _)holder = true; return function(/* ...args */){ var that = this , _length = arguments.length , i = 0, j = 0, _args; if(!holder && !_length)return invoke(fn, args, that); _args = args.slice(); if(holder)for(;length > i; i++)if(_args[i] === _)_args[i] = arguments[j++]; while(_length > j)_args.push(arguments[j++]); return invoke(fn, _args, that); } } // Optional / simple context binding function ctx(fn, that, length){ assertFunction(fn); if(~length && that === undefined)return fn; switch(length){ case 1: return function(a){ return fn.call(that, a); } case 2: return function(a, b){ return fn.call(that, a, b); } case 3: return function(a, b, c){ return fn.call(that, a, b, c); } } return function(/* ...args */){ return fn.apply(that, arguments); } } // Fast apply // http://jsperf.lnkit.com/fast-apply/5 function invoke(fn, args, that){ var un = that === undefined; switch(args.length | 0){ case 0: return un ? fn() : fn.call(that); case 1: return un ? fn(args[0]) : fn.call(that, args[0]); case 2: return un ? fn(args[0], args[1]) : fn.call(that, args[0], args[1]); case 3: return un ? fn(args[0], args[1], args[2]) : fn.call(that, args[0], args[1], args[2]); case 4: return un ? fn(args[0], args[1], args[2], args[3]) : fn.call(that, args[0], args[1], args[2], args[3]); case 5: return un ? fn(args[0], args[1], args[2], args[3], args[4]) : fn.call(that, args[0], args[1], args[2], args[3], args[4]); } return fn.apply(that, args); } // Object: var create = Object.create , getPrototypeOf = Object.getPrototypeOf , setPrototypeOf = Object.setPrototypeOf , defineProperty = Object.defineProperty , defineProperties = Object.defineProperties , getOwnDescriptor = Object.getOwnPropertyDescriptor , getKeys = Object.keys , getNames = Object.getOwnPropertyNames , getSymbols = Object.getOwnPropertySymbols , isFrozen = Object.isFrozen , has = ctx(call, ObjectProto[HAS_OWN], 2) // Dummy, fix for not array-like ES3 string in es5 module , ES5Object = Object , Dict; function toObject(it){ return ES5Object(assertDefined(it)); } function returnIt(it){ return it; } function returnThis(){ return this; } function get(object, key){ if(has(object, key))return object[key]; } function ownKeys(it){ assertObject(it); return getSymbols ? getNames(it).concat(getSymbols(it)) : getNames(it); } // 19.1.2.1 Object.assign(target, source, ...) var assign = Object.assign || function(target, source){ var T = Object(assertDefined(target)) , l = arguments.length , i = 1; while(l > i){ var S = ES5Object(arguments[i++]) , keys = getKeys(S) , length = keys.length , j = 0 , key; while(length > j)T[key = keys[j++]] = S[key]; } return T; } function keyOf(object, el){ var O = toObject(object) , keys = getKeys(O) , length = keys.length , index = 0 , key; while(length > index)if(O[key = keys[index++]] === el)return key; } // Array // array('str1,str2,str3') => ['str1', 'str2', 'str3'] function array(it){ return String(it).split(','); } var push = ArrayProto.push , unshift = ArrayProto.unshift , slice = ArrayProto.slice , splice = ArrayProto.splice , indexOf = ArrayProto.indexOf , forEach = ArrayProto[FOR_EACH]; /* * 0 -> forEach * 1 -> map * 2 -> filter * 3 -> some * 4 -> every * 5 -> find * 6 -> findIndex */ function createArrayMethod(type){ var isMap = type == 1 , isFilter = type == 2 , isSome = type == 3 , isEvery = type == 4 , isFindIndex = type == 6 , noholes = type == 5 || isFindIndex; return function(callbackfn/*, that = undefined */){ var O = Object(assertDefined(this)) , that = arguments[1] , self = ES5Object(O) , f = ctx(callbackfn, that, 3) , length = toLength(self.length) , index = 0 , result = isMap ? Array(length) : isFilter ? [] : undefined , val, res; for(;length > index; index++)if(noholes || index in self){ val = self[index]; res = f(val, index, O); if(type){ if(isMap)result[index] = res; // map else if(res)switch(type){ case 3: return true; // some case 5: return val; // find case 6: return index; // findIndex case 2: result.push(val); // filter } else if(isEvery)return false; // every } } return isFindIndex ? -1 : isSome || isEvery ? isEvery : result; } } function createArrayContains(isContains){ return function(el /*, fromIndex = 0 */){ var O = toObject(this) , length = toLength(O.length) , index = toIndex(arguments[1], length); if(isContains && el != el){ for(;length > index; index++)if(sameNaN(O[index]))return isContains || index; } else for(;length > index; index++)if(isContains || index in O){ if(O[index] === el)return isContains || index; } return !isContains && -1; } } function generic(A, B){ // strange IE quirks mode bug -> use typeof vs isFunction return typeof A == 'function' ? A : B; } // Math var MAX_SAFE_INTEGER = 0x1fffffffffffff // pow(2, 53) - 1 == 9007199254740991 , pow = Math.pow , abs = Math.abs , ceil = Math.ceil , floor = Math.floor , max = Math.max , min = Math.min , random = Math.random , trunc = Math.trunc || function(it){ return (it > 0 ? floor : ceil)(it); } // 20.1.2.4 Number.isNaN(number) function sameNaN(number){ return number != number; } // 7.1.4 ToInteger function toInteger(it){ return isNaN(it) ? 0 : trunc(it); } // 7.1.15 ToLength function toLength(it){ return it > 0 ? min(toInteger(it), MAX_SAFE_INTEGER) : 0; } function toIndex(index, length){ var index = toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); } function lz(num){ return num > 9 ? num : '0' + num; } function createReplacer(regExp, replace, isStatic){ var replacer = isObject(replace) ? function(part){ return replace[part]; } : replace; return function(it){ return String(isStatic ? it : this).replace(regExp, replacer); } } function createPointAt(toString){ return function(pos){ var s = String(assertDefined(this)) , i = toInteger(pos) , l = s.length , a, b; if(i < 0 || i >= l)return toString ? '' : undefined; a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? toString ? s.charAt(i) : a : toString ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; } } // Assertion & errors var REDUCE_ERROR = 'Reduce of empty object with no initial value'; function assert(condition, msg1, msg2){ if(!condition)throw TypeError(msg2 ? msg1 + msg2 : msg1); } function assertDefined(it){ if(it == undefined)throw TypeError('Function called on null or undefined'); return it; } function assertFunction(it){ assert(isFunction(it), it, ' is not a function!'); return it; } function assertObject(it){ assert(isObject(it), it, ' is not an object!'); return it; } function assertInstance(it, Constructor, name){ assert(it instanceof Constructor, name, ": use the 'new' operator!"); } // Property descriptors & Symbol function descriptor(bitmap, value){ return { enumerable : !(bitmap & 1), configurable: !(bitmap & 2), writable : !(bitmap & 4), value : value } } function simpleSet(object, key, value){ object[key] = value; return object; } function createDefiner(bitmap){ return DESC ? function(object, key, value){ return defineProperty(object, key, descriptor(bitmap, value)); } : simpleSet; } function uid(key){ return SYMBOL + '(' + key + ')_' + (++sid + random())[TO_STRING](36); } function getWellKnownSymbol(name, setter){ return (Symbol && Symbol[name]) || (setter ? Symbol : safeSymbol)(SYMBOL + DOT + name); } // The engine works fine with descriptors? Thank's IE8 for his funny defineProperty. var DESC = !!function(){ try { return defineProperty({}, 'a', {get: function(){ return 2 }}).a == 2; } catch(e){} }() , sid = 0 , hidden = createDefiner(1) , set = Symbol ? simpleSet : hidden , safeSymbol = Symbol || uid; function assignHidden(target, src){ for(var key in src)hidden(target, key, src[key]); return target; } var SYMBOL_UNSCOPABLES = getWellKnownSymbol('unscopables') , ArrayUnscopables = ArrayProto[SYMBOL_UNSCOPABLES] || {} , SYMBOL_TAG = getWellKnownSymbol(TO_STRING_TAG) , SYMBOL_SPECIES = getWellKnownSymbol('species') , SYMBOL_ITERATOR; function setSpecies(C){ if(DESC && (framework || !isNative(C)))defineProperty(C, SYMBOL_SPECIES, { configurable: true, get: returnThis }); } /****************************************************************************** * Module : common.export * ******************************************************************************/ var NODE = cof(process) == PROCESS , core = {} , path = framework ? global : core , old = global.core , exportGlobal // type bitmap , FORCED = 1 , GLOBAL = 2 , STATIC = 4 , PROTO = 8 , BIND = 16 , WRAP = 32; function $define(type, name, source){ var key, own, out, exp , isGlobal = type & GLOBAL , target = isGlobal ? global : (type & STATIC) ? global[name] : (global[name] || ObjectProto)[PROTOTYPE] , exports = isGlobal ? core : core[name] || (core[name] = {}); if(isGlobal)source = name; for(key in source){ // there is a similar native own = !(type & FORCED) && target && key in target && (!isFunction(target[key]) || isNative(target[key])); // export native or passed out = (own ? target : source)[key]; // prevent global pollution for namespaces if(!framework && isGlobal && !isFunction(target[key]))exp = source[key]; // bind timers to global for call from export context else if(type & BIND && own)exp = ctx(out, global); // wrap global constructors for prevent change them in library else if(type & WRAP && !framework && target[key] == out){ exp = function(param){ return this instanceof out ? new out(param) : out(param); } exp[PROTOTYPE] = out[PROTOTYPE]; } else exp = type & PROTO && isFunction(out) ? ctx(call, out) : out; // extend global if(framework && target && !own){ if(isGlobal)target[key] = out; else delete target[key] && hidden(target, key, out); } // export if(exports[key] != out)hidden(exports, key, exp); } } // CommonJS export if(typeof module != 'undefined' && module.exports)module.exports = core; // RequireJS export else if(isFunction(define) && define.amd)define(function(){return core}); // Export to global object else exportGlobal = true; if(exportGlobal || framework){ core.noConflict = function(){ global.core = old; return core; } global.core = core; } /****************************************************************************** * Module : common.iterators * ******************************************************************************/ SYMBOL_ITERATOR = getWellKnownSymbol(ITERATOR); var ITER = safeSymbol('iter') , KEY = 1 , VALUE = 2 , Iterators = {} , IteratorPrototype = {} // Safari has byggy iterators w/o `next` , BUGGY_ITERATORS = 'keys' in ArrayProto && !('next' in [].keys()); // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() setIterator(IteratorPrototype, returnThis); function setIterator(O, value){ hidden(O, SYMBOL_ITERATOR, value); // Add iterator for FF iterator protocol FF_ITERATOR in ArrayProto && hidden(O, FF_ITERATOR, value); } function createIterator(Constructor, NAME, next, proto){ Constructor[PROTOTYPE] = create(proto || IteratorPrototype, {next: descriptor(1, next)}); setToStringTag(Constructor, NAME + ' Iterator'); } function defineIterator(Constructor, NAME, value, DEFAULT){ var proto = Constructor[PROTOTYPE] , iter = get(proto, SYMBOL_ITERATOR) || get(proto, FF_ITERATOR) || (DEFAULT && get(proto, DEFAULT)) || value; if(framework){ // Define iterator setIterator(proto, iter); if(iter !== value){ var iterProto = getPrototypeOf(iter.call(new Constructor)); // Set @@toStringTag to native iterators setToStringTag(iterProto, NAME + ' Iterator', true); // FF fix has(proto, FF_ITERATOR) && setIterator(iterProto, returnThis); } } // Plug for library Iterators[NAME] = iter; // FF & v8 fix Iterators[NAME + ' Iterator'] = returnThis; return iter; } function defineStdIterators(Base, NAME, Constructor, next, DEFAULT, IS_SET){ function createIter(kind){ return function(){ return new Constructor(this, kind); } } createIterator(Constructor, NAME, next); var entries = createIter(KEY+VALUE) , values = createIter(VALUE); if(DEFAULT == VALUE)values = defineIterator(Base, NAME, values, 'values'); else entries = defineIterator(Base, NAME, entries, 'entries'); if(DEFAULT){ $define(PROTO + FORCED * BUGGY_ITERATORS, NAME, { entries: entries, keys: IS_SET ? values : createIter(KEY), values: values }); } } function iterResult(done, value){ return {value: value, done: !!done}; } function isIterable(it){ var O = Object(it) , Symbol = global[SYMBOL] , hasExt = (Symbol && Symbol[ITERATOR] || FF_ITERATOR) in O; return hasExt || SYMBOL_ITERATOR in O || has(Iterators, classof(O)); } function getIterator(it){ var Symbol = global[SYMBOL] , ext = it[Symbol && Symbol[ITERATOR] || FF_ITERATOR] , getIter = ext || it[SYMBOL_ITERATOR] || Iterators[classof(it)]; return assertObject(getIter.call(it)); } function stepCall(fn, value, entries){ return entries ? invoke(fn, value) : fn(value); } function checkDangerIterClosing(fn){ var danger = true; var O = { next: function(){ throw 1 }, 'return': function(){ danger = false } }; O[SYMBOL_ITERATOR] = returnThis; try { fn(O); } catch(e){} return danger; } function closeIterator(iterator){ var ret = iterator['return']; if(ret !== undefined)ret.call(iterator); } function safeIterClose(exec, iterator){ try { exec(iterator); } catch(e){ closeIterator(iterator); throw e; } } function forOf(iterable, entries, fn, that){ safeIterClose(function(iterator){ var f = ctx(fn, that, entries ? 2 : 1) , step; while(!(step = iterator.next()).done)if(stepCall(f, step.value, entries) === false){ return closeIterator(iterator); } }, getIterator(iterable)); } /****************************************************************************** * Module : es6.symbol * ******************************************************************************/ // ECMAScript 6 symbols shim !function(TAG, SymbolRegistry, AllSymbols, setter){ // 19.4.1.1 Symbol([description]) if(!isNative(Symbol)){ Symbol = function(description){ assert(!(this instanceof Symbol), SYMBOL + ' is not a ' + CONSTRUCTOR); var tag = uid(description) , sym = set(create(Symbol[PROTOTYPE]), TAG, tag); AllSymbols[tag] = sym; DESC && setter && defineProperty(ObjectProto, tag, { configurable: true, set: function(value){ hidden(this, tag, value); } }); return sym; } hidden(Symbol[PROTOTYPE], TO_STRING, function(){ return this[TAG]; }); } $define(GLOBAL + WRAP, {Symbol: Symbol}); var symbolStatics = { // 19.4.2.1 Symbol.for(key) 'for': function(key){ return has(SymbolRegistry, key += '') ? SymbolRegistry[key] : SymbolRegistry[key] = Symbol(key); }, // 19.4.2.4 Symbol.iterator iterator: SYMBOL_ITERATOR || getWellKnownSymbol(ITERATOR), // 19.4.2.5 Symbol.keyFor(sym) keyFor: part.call(keyOf, SymbolRegistry), // 19.4.2.10 Symbol.species species: SYMBOL_SPECIES, // 19.4.2.13 Symbol.toStringTag toStringTag: SYMBOL_TAG = getWellKnownSymbol(TO_STRING_TAG, true), // 19.4.2.14 Symbol.unscopables unscopables: SYMBOL_UNSCOPABLES, pure: safeSymbol, set: set, useSetter: function(){setter = true}, useSimple: function(){setter = false} }; // 19.4.2.2 Symbol.hasInstance // 19.4.2.3 Symbol.isConcatSpreadable // 19.4.2.6 Symbol.match // 19.4.2.8 Symbol.replace // 19.4.2.9 Symbol.search // 19.4.2.11 Symbol.split // 19.4.2.12 Symbol.toPrimitive forEach.call(array('hasInstance,isConcatSpreadable,match,replace,search,split,toPrimitive'), function(it){ symbolStatics[it] = getWellKnownSymbol(it); } ); $define(STATIC, SYMBOL, symbolStatics); setToStringTag(Symbol, SYMBOL); $define(STATIC + FORCED * !isNative(Symbol), OBJECT, { // 19.1.2.7 Object.getOwnPropertyNames(O) getOwnPropertyNames: function(it){ var names = getNames(toObject(it)), result = [], key, i = 0; while(names.length > i)has(AllSymbols, key = names[i++]) || result.push(key); return result; }, // 19.1.2.8 Object.getOwnPropertySymbols(O) getOwnPropertySymbols: function(it){ var names = getNames(toObject(it)), result = [], key, i = 0; while(names.length > i)has(AllSymbols, key = names[i++]) && result.push(AllSymbols[key]); return result; } }); // 20.2.1.9 Math[@@toStringTag] setToStringTag(Math, MATH, true); // 24.3.3 JSON[@@toStringTag] setToStringTag(global.JSON, 'JSON', true); }(safeSymbol('tag'), {}, {}, true); /****************************************************************************** * Module : es6.object.statics * ******************************************************************************/ !function(){ var objectStatic = { // 19.1.3.1 Object.assign(target, source) assign: assign, // 19.1.3.10 Object.is(value1, value2) is: function(x, y){ return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; } }; // 19.1.3.19 Object.setPrototypeOf(O, proto) // Works with __proto__ only. Old v8 can't works with null proto objects. '__proto__' in ObjectProto && function(buggy, set){ try { set = ctx(call, getOwnDescriptor(ObjectProto, '__proto__').set, 2); set({}, ArrayProto); } catch(e){ buggy = true } objectStatic.setPrototypeOf = setPrototypeOf = setPrototypeOf || function(O, proto){ assertObject(O); assert(proto === null || isObject(proto), proto, ": can't set as prototype!"); if(buggy)O.__proto__ = proto; else set(O, proto); return O; } }(); $define(STATIC, OBJECT, objectStatic); }(); /****************************************************************************** * Module : es6.object.prototype * ******************************************************************************/ !function(tmp){ // 19.1.3.6 Object.prototype.toString() tmp[SYMBOL_TAG] = DOT; if(cof(tmp) != DOT)hidden(ObjectProto, TO_STRING, function(){ return '[object ' + classof(this) + ']'; }); }({}); /****************************************************************************** * Module : es6.object.statics-accept-primitives * ******************************************************************************/ !function(){ // Object static methods accept primitives function wrapObjectMethod(key, MODE){ var fn = Object[key] , exp = core[OBJECT][key] , f = 0 , o = {}; if(!exp || isNative(exp)){ o[key] = MODE == 1 ? function(it){ return isObject(it) ? fn(it) : it; } : MODE == 2 ? function(it){ return isObject(it) ? fn(it) : true; } : MODE == 3 ? function(it){ return isObject(it) ? fn(it) : false; } : MODE == 4 ? function(it, key){ return fn(toObject(it), key); } : function(it){ return fn(toObject(it)); }; try { fn(DOT) } catch(e){ f = 1 } $define(STATIC + FORCED * f, OBJECT, o); } } wrapObjectMethod('freeze', 1); wrapObjectMethod('seal', 1); wrapObjectMethod('preventExtensions', 1); wrapObjectMethod('isFrozen', 2); wrapObjectMethod('isSealed', 2); wrapObjectMethod('isExtensible', 3); wrapObjectMethod('getOwnPropertyDescriptor', 4); wrapObjectMethod('getPrototypeOf'); wrapObjectMethod('keys'); wrapObjectMethod('getOwnPropertyNames'); }(); /****************************************************************************** * Module : es6.function * ******************************************************************************/ !function(NAME){ // 19.2.4.2 name NAME in FunctionProto || (DESC && defineProperty(FunctionProto, NAME, { configurable: true, get: function(){ var match = String(this).match(/^\s*function ([^ (]*)/) , name = match ? match[1] : ''; has(this, NAME) || defineProperty(this, NAME, descriptor(5, name)); return name; }, set: function(value){ has(this, NAME) || defineProperty(this, NAME, descriptor(0, value)); } })); }('name'); /****************************************************************************** * Module : es6.number.constructor * ******************************************************************************/ Number('0o1') && Number('0b1') || function(_Number, NumberProto){ function toNumber(it){ if(isObject(it))it = toPrimitive(it); if(typeof it == 'string' && it.length > 2 && it.charCodeAt(0) == 48){ var binary = false; switch(it.charCodeAt(1)){ case 66 : case 98 : binary = true; case 79 : case 111 : return parseInt(it.slice(2), binary ? 2 : 8); } } return +it; } function toPrimitive(it){ var fn, val; if(isFunction(fn = it.valueOf) && !isObject(val = fn.call(it)))return val; if(isFunction(fn = it[TO_STRING]) && !isObject(val = fn.call(it)))return val; throw TypeError("Can't convert object to number"); } Number = function Number(it){ return this instanceof Number ? new _Number(toNumber(it)) : toNumber(it); } forEach.call(DESC ? getNames(_Number) : array('MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY'), function(key){ key in Number || defineProperty(Number, key, getOwnDescriptor(_Number, key)); }); Number[PROTOTYPE] = NumberProto; NumberProto[CONSTRUCTOR] = Number; hidden(global, NUMBER, Number); }(Number, Number[PROTOTYPE]); /****************************************************************************** * Module : es6.number.statics * ******************************************************************************/ !function(isInteger){ $define(STATIC, NUMBER, { // 20.1.2.1 Number.EPSILON EPSILON: pow(2, -52), // 20.1.2.2 Number.isFinite(number) isFinite: function(it){ return typeof it == 'number' && isFinite(it); }, // 20.1.2.3 Number.isInteger(number) isInteger: isInteger, // 20.1.2.4 Number.isNaN(number) isNaN: sameNaN, // 20.1.2.5 Number.isSafeInteger(number) isSafeInteger: function(number){ return isInteger(number) && abs(number) <= MAX_SAFE_INTEGER; }, // 20.1.2.6 Number.MAX_SAFE_INTEGER MAX_SAFE_INTEGER: MAX_SAFE_INTEGER, // 20.1.2.10 Number.MIN_SAFE_INTEGER MIN_SAFE_INTEGER: -MAX_SAFE_INTEGER, // 20.1.2.12 Number.parseFloat(string) parseFloat: parseFloat, // 20.1.2.13 Number.parseInt(string, radix) parseInt: parseInt }); // 20.1.2.3 Number.isInteger(number) }(Number.isInteger || function(it){ return !isObject(it) && isFinite(it) && floor(it) === it; }); /****************************************************************************** * Module : es6.math * ******************************************************************************/ // ECMAScript 6 shim !function(){ // 20.2.2.28 Math.sign(x) var E = Math.E , exp = Math.exp , log = Math.log , sqrt = Math.sqrt , sign = Math.sign || function(x){ return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1; }; // 20.2.2.5 Math.asinh(x) function asinh(x){ return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : log(x + sqrt(x * x + 1)); } // 20.2.2.14 Math.expm1(x) function expm1(x){ return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : exp(x) - 1; } $define(STATIC, MATH, { // 20.2.2.3 Math.acosh(x) acosh: function(x){ return (x = +x) < 1 ? NaN : isFinite(x) ? log(x / E + sqrt(x + 1) * sqrt(x - 1) / E) + 1 : x; }, // 20.2.2.5 Math.asinh(x) asinh: asinh, // 20.2.2.7 Math.atanh(x) atanh: function(x){ return (x = +x) == 0 ? x : log((1 + x) / (1 - x)) / 2; }, // 20.2.2.9 Math.cbrt(x) cbrt: function(x){ return sign(x = +x) * pow(abs(x), 1 / 3); }, // 20.2.2.11 Math.clz32(x) clz32: function(x){ return (x >>>= 0) ? 32 - x[TO_STRING](2).length : 32; }, // 20.2.2.12 Math.cosh(x) cosh: function(x){ return (exp(x = +x) + exp(-x)) / 2; }, // 20.2.2.14 Math.expm1(x) expm1: expm1, // 20.2.2.16 Math.fround(x) // TODO: fallback for IE9- fround: function(x){ return new Float32Array([x])[0]; }, // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) hypot: function(value1, value2){ var sum = 0 , len1 = arguments.length , len2 = len1 , args = Array(len1) , larg = -Infinity , arg; while(len1--){ arg = args[len1] = +arguments[len1]; if(arg == Infinity || arg == -Infinity)return Infinity; if(arg > larg)larg = arg; } larg = arg || 1; while(len2--)sum += pow(args[len2] / larg, 2); return larg * sqrt(sum); }, // 20.2.2.18 Math.imul(x, y) imul: function(x, y){ var UInt16 = 0xffff , xn = +x , yn = +y , xl = UInt16 & xn , yl = UInt16 & yn; return 0 | xl * yl + ((UInt16 & xn >>> 16) * yl + xl * (UInt16 & yn >>> 16) << 16 >>> 0); }, // 20.2.2.20 Math.log1p(x) log1p: function(x){ return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : log(1 + x); }, // 20.2.2.21 Math.log10(x) log10: function(x){ return log(x) / Math.LN10; }, // 20.2.2.22 Math.log2(x) log2: function(x){ return log(x) / Math.LN2; }, // 20.2.2.28 Math.sign(x) sign: sign, // 20.2.2.30 Math.sinh(x) sinh: function(x){ return (abs(x = +x) < 1) ? (expm1(x) - expm1(-x)) / 2 : (exp(x - 1) - exp(-x - 1)) * (E / 2); }, // 20.2.2.33 Math.tanh(x) tanh: function(x){ var a = expm1(x = +x) , b = expm1(-x); return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x)); }, // 20.2.2.34 Math.trunc(x) trunc: trunc }); }(); /****************************************************************************** * Module : es6.string * ******************************************************************************/ !function(fromCharCode){ function assertNotRegExp(it){ if(cof(it) == REGEXP)throw TypeError(); } $define(STATIC, STRING, { // 21.1.2.2 String.fromCodePoint(...codePoints) fromCodePoint: function(x){ var res = [] , len = arguments.length , i = 0 , code while(len > i){ code = +arguments[i++]; if(toIndex(code, 0x10ffff) !== code)throw RangeError(code + ' is not a valid code point'); res.push(code < 0x10000 ? fromCharCode(code) : fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00) ); } return res.join(''); }, // 21.1.2.4 String.raw(callSite, ...substitutions) raw: function(callSite){ var raw = toObject(callSite.raw) , len = toLength(raw.length) , sln = arguments.length , res = [] , i = 0; while(len > i){ res.push(String(raw[i++])); if(i < sln)res.push(String(arguments[i])); } return res.join(''); } }); $define(PROTO, STRING, { // 21.1.3.3 String.prototype.codePointAt(pos) codePointAt: createPointAt(false), // 21.1.3.6 String.prototype.endsWith(searchString [, endPosition]) endsWith: function(searchString /*, endPosition = @length */){ assertNotRegExp(searchString); var that = String(assertDefined(this)) , endPosition = arguments[1] , len = toLength(that.length) , end = endPosition === undefined ? len : min(toLength(endPosition), len); searchString += ''; return that.slice(end - searchString.length, end) === searchString; }, // 21.1.3.7 String.prototype.includes(searchString, position = 0) includes: function(searchString /*, position = 0 */){ assertNotRegExp(searchString); return !!~String(assertDefined(this)).indexOf(searchString, arguments[1]); }, // 21.1.3.13 String.prototype.repeat(count) repeat: function(count){ var str = String(assertDefined(this)) , res = '' , n = toInteger(count); if(0 > n || n == Infinity)throw RangeError("Count can't be negative"); for(;n > 0; (n >>>= 1) && (str += str))if(n & 1)res += str; return res; }, // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) startsWith: function(searchString /*, position = 0 */){ assertNotRegExp(searchString); var that = String(assertDefined(this)) , index = toLength(min(arguments[1], that.length)); searchString += ''; return that.slice(index, index + searchString.length) === searchString; } }); }(String.fromCharCode); /****************************************************************************** * Module : es6.array.statics * ******************************************************************************/ !function(){ $define(STATIC + FORCED * checkDangerIterClosing(Array.from), ARRAY, { // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) from: function(arrayLike/*, mapfn = undefined, thisArg = undefined*/){ var O = Object(assertDefined(arrayLike)) , mapfn = arguments[1] , mapping = mapfn !== undefined , f = mapping ? ctx(mapfn, arguments[2], 2) : undefined , index = 0 , length, result, step; if(isIterable(O)){ result = new (generic(this, Array)); safeIterClose(function(iterator){ for(; !(step = iterator.next()).done; index++){ result[index] = mapping ? f(step.value, index) : step.value; } }, getIterator(O)); } else { result = new (generic(this, Array))(length = toLength(O.length)); for(; length > index; index++){ result[index] = mapping ? f(O[index], index) : O[index]; } } result.length = index; return result; } }); $define(STATIC, ARRAY, { // 22.1.2.3 Array.of( ...items) of: function(/* ...args */){ var index = 0 , length = arguments.length , result = new (generic(this, Array))(length); while(length > index)result[index] = arguments[index++]; result.length = length; return result; } }); setSpecies(Array); }(); /****************************************************************************** * Module : es6.array.prototype * ******************************************************************************/ !function(){ $define(PROTO, ARRAY, { // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) copyWithin: function(target /* = 0 */, start /* = 0, end = @length */){ var O = Object(assertDefined(this)) , len = toLength(O.length) , to = toIndex(target, len) , from = toIndex(start, len) , end = arguments[2] , fin = end === undefined ? len : toIndex(end, len) , count = min(fin - from, len - to) , inc = 1; if(from < to && to < from + count){ inc = -1; from = from + count - 1; to = to + count - 1; } while(count-- > 0){ if(from in O)O[to] = O[from]; else delete O[to]; to += inc; from += inc; } return O; }, // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) fill: function(value /*, start = 0, end = @length */){ var O = Object(assertDefined(this)) , length = toLength(O.length) , index = toIndex(arguments[1], length) , end = arguments[2] , endPos = end === undefined ? length : toIndex(end, length); while(endPos > index)O[index++] = value; return O; }, // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) find: createArrayMethod(5), // 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined) findIndex: createArrayMethod(6) }); if(framework){ // 22.1.3.31 Array.prototype[@@unscopables] forEach.call(array('find,findIndex,fill,copyWithin,entries,keys,values'), function(it){ ArrayUnscopables[it] = true; }); SYMBOL_UNSCOPABLES in ArrayProto || hidden(ArrayProto, SYMBOL_UNSCOPABLES, ArrayUnscopables); } }(); /****************************************************************************** * Module : es6.iterators * ******************************************************************************/ !function(at){ // 22.1.3.4 Array.prototype.entries() // 22.1.3.13 Array.prototype.keys() // 22.1.3.29 Array.prototype.values() // 22.1.3.30 Array.prototype[@@iterator]() defineStdIterators(Array, ARRAY, function(iterated, kind){ set(this, ITER, {o: toObject(iterated), i: 0, k: kind}); // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function(){ var iter = this[ITER] , O = iter.o , kind = iter.k , index = iter.i++; if(!O || index >= O.length){ iter.o = undefined; return iterResult(1); } if(kind == KEY) return iterResult(0, index); if(kind == VALUE)return iterResult(0, O[index]); return iterResult(0, [index, O[index]]); }, VALUE); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators[ARGUMENTS] = Iterators[ARRAY]; // 21.1.3.27 String.prototype[@@iterator]() defineStdIterators(String, STRING, function(iterated){ set(this, ITER, {o: String(iterated), i: 0}); // 21.1.5.2.1 %StringIteratorPrototype%.next() }, function(){ var iter = this[ITER] , O = iter.o , index = iter.i , point; if(index >= O.length)return iterResult(1); point = at.call(O, index); iter.i += point.length; return iterResult(0, point); }); }(createPointAt(true)); /****************************************************************************** * Module : es6.regexp * ******************************************************************************/ DESC && !function(RegExpProto, _RegExp){ // RegExp allows a regex with flags as the pattern if(!function(){try{return RegExp(/a/g, 'i') == '/a/i'}catch(e){}}()){ RegExp = function RegExp(pattern, flags){ return new _RegExp(cof(pattern) == REGEXP && flags !== undefined ? pattern.source : pattern, flags); } forEach.call(getNames(_RegExp), function(key){ key in RegExp || defineProperty(RegExp, key, { configurable: true, get: function(){ return _RegExp[key] }, set: function(it){ _RegExp[key] = it } }); }); RegExpProto[CONSTRUCTOR] = RegExp; RegExp[PROTOTYPE] = RegExpProto; hidden(global, REGEXP, RegExp); } // 21.2.5.3 get RegExp.prototype.flags() if(/./g.flags != 'g')defineProperty(RegExpProto, 'flags', { configurable: true, get: createReplacer(/^.*\/(\w*)$/, '$1') }); setSpecies(RegExp); }(RegExp[PROTOTYPE], RegExp); /****************************************************************************** * Module : web.immediate * ******************************************************************************/ // setImmediate shim // Node.js 0.9+ & IE10+ has setImmediate, else: isFunction(setImmediate) && isFunction(clearImmediate) || function(ONREADYSTATECHANGE){ var postMessage = global.postMessage , addEventListener = global.addEventListener , MessageChannel = global.MessageChannel , counter = 0 , queue = {} , defer, channel, port; setImmediate = function(fn){ var args = [], i = 1; while(arguments.length > i)args.push(arguments[i++]); queue[++counter] = function(){ invoke(isFunction(fn) ? fn : Function(fn), args); } defer(counter); return counter; } clearImmediate = function(id){ delete queue[id]; } function run(id){ if(has(queue, id)){ var fn = queue[id]; delete queue[id]; fn(); } } function listner(event){ run(event.data); } // Node.js 0.8- if(NODE){ defer = function(id){ nextTick(part.call(run, id)); } // Modern browsers, skip implementation for WebWorkers // IE8 has postMessage, but it's sync & typeof its postMessage is object } else if(addEventListener && isFunction(postMessage) && !global.importScripts){ defer = function(id){ postMessage(id, '*'); } addEventListener('message', listner, false); // WebWorkers } else if(isFunction(MessageChannel)){ channel = new MessageChannel; port = channel.port2; channel.port1.onmessage = listner; defer = ctx(port.postMessage, port, 1); // IE8- } else if(document && ONREADYSTATECHANGE in document[CREATE_ELEMENT]('script')){ defer = function(id){ html.appendChild(document[CREATE_ELEMENT]('script'))[ONREADYSTATECHANGE] = function(){ html.removeChild(this); run(id); } } // Rest old browsers } else { defer = function(id){ setTimeout(run, 0, id); } } }('onreadystatechange'); $define(GLOBAL + BIND, { setImmediate: setImmediate, clearImmediate: clearImmediate }); /****************************************************************************** * Module : es6.promise * ******************************************************************************/ // ES6 promises shim // Based on https://github.com/getify/native-promise-only/ !function(Promise, test){ isFunction(Promise) && isFunction(Promise.resolve) && Promise.resolve(test = new Promise(function(){})) == test || function(asap, RECORD){ function isThenable(it){ var then; if(isObject(it))then = it.then; return isFunction(then) ? then : false; } function handledRejectionOrHasOnRejected(promise){ var record = promise[RECORD] , chain = record.c , i = 0 , react; if(record.h)return true; while(chain.length > i){ react = chain[i++]; if(react.fail || handledRejectionOrHasOnRejected(react.P))return true; } } function notify(record, reject){ var chain = record.c; if(reject || chain.length)asap(function(){ var promise = record.p , value = record.v , ok = record.s == 1 , i = 0; if(reject && !handledRejectionOrHasOnRejected(promise)){ setTimeout(function(){ if(!handledRejectionOrHasOnRejected(promise)){ if(NODE){ if(!process.emit('unhandledRejection', value, promise)){ // default node.js behavior } } else if(isFunction(console.error)){ console.error('Unhandled promise rejection', value); } } }, 1e3); } else while(chain.length > i)!function(react){ var cb = ok ? react.ok : react.fail , ret, then; try { if(cb){ if(!ok)record.h = true; ret = cb === true ? value : cb(value); if(ret === react.P){ react.rej(TypeError(PROMISE + '-chain cycle')); } else if(then = isThenable(ret)){ then.call(ret, react.res, react.rej); } else react.res(ret); } else react.rej(value); } catch(err){ react.rej(err); } }(chain[i++]); chain.length = 0; }); } function resolve(value){ var record = this , then, wrapper; if(record.d)return; record.d = true; record = record.r || record; // unwrap try { if(then = isThenable(value)){ wrapper = {r: record, d: false}; // wrap then.call(value, ctx(resolve, wrapper, 1), ctx(reject, wrapper, 1)); } else { record.v = value; record.s = 1; notify(record); } } catch(err){ reject.call(wrapper || {r: record, d: false}, err); // wrap } } function reject(value){ var record = this; if(record.d)return; record.d = true; record = record.r || record; // unwrap record.v = value; record.s = 2; notify(record, true); } function getConstructor(C){ var S = assertObject(C)[SYMBOL_SPECIES]; return S != undefined ? S : C; } // 25.4.3.1 Promise(executor) Promise = function(executor){ assertFunction(executor); assertInstance(this, Promise, PROMISE); var record = { p: this, // promise c: [], // chain s: 0, // state d: false, // done v: undefined, // value h: false // handled rejection }; hidden(this, RECORD, record); try { executor(ctx(resolve, record, 1), ctx(reject, record, 1)); } catch(err){ reject.call(record, err); } } assignHidden(Promise[PROTOTYPE], { // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) then: function(onFulfilled, onRejected){ var S = assertObject(assertObject(this)[CONSTRUCTOR])[SYMBOL_SPECIES]; var react = { ok: isFunction(onFulfilled) ? onFulfilled : true, fail: isFunction(onRejected) ? onRejected : false } , P = react.P = new (S != undefined ? S : Promise)(function(resolve, reject){ react.res = assertFunction(resolve); react.rej = assertFunction(reject); }), record = this[RECORD]; record.c.push(react); record.s && notify(record); return P; }, // 25.4.5.1 Promise.prototype.catch(onRejected) 'catch': function(onRejected){ return this.then(undefined, onRejected); } }); assignHidden(Promise, { // 25.4.4.1 Promise.all(iterable) all: function(iterable){ var Promise = getConstructor(this) , values = []; return new Promise(function(resolve, reject){ forOf(iterable, false, push, values); var remaining = values.length , results = Array(remaining); if(remaining)forEach.call(values, function(promise, index){ Promise.resolve(promise).then(function(value){ results[index] = value; --remaining || resolve(results); }, reject); }); else resolve(results); }); }, // 25.4.4.4 Promise.race(iterable) race: function(iterable){ var Promise = getConstructor(this); return new Promise(function(resolve, reject){ forOf(iterable, false, function(promise){ Promise.resolve(promise).then(resolve, reject); }); }); }, // 25.4.4.5 Promise.reject(r) reject: function(r){ return new (getConstructor(this))(function(resolve, reject){ reject(r); }); }, // 25.4.4.6 Promise.resolve(x) resolve: function(x){ return isObject(x) && RECORD in x && getPrototypeOf(x) === this[PROTOTYPE] ? x : new (getConstructor(this))(function(resolve, reject){ resolve(x); }); } }); }(nextTick || setImmediate, safeSymbol('record')); setToStringTag(Promise, PROMISE); setSpecies(Promise); $define(GLOBAL + FORCED * !isNative(Promise), {Promise: Promise}); }(global[PROMISE]); /****************************************************************************** * Module : es6.collections * ******************************************************************************/ // ECMAScript 6 collections shim !function(){ var UID = safeSymbol('uid') , O1 = safeSymbol('O1') , WEAK = safeSymbol('weak') , LEAK = safeSymbol('leak') , LAST = safeSymbol('last') , FIRST = safeSymbol('first') , SIZE = DESC ? safeSymbol('size') : 'size' , uid = 0 , tmp = {}; function getCollection(C, NAME, methods, commonMethods, isMap, isWeak){ var ADDER = isMap ? 'set' : 'add' , proto = C && C[PROTOTYPE] , O = {}; function initFromIterable(that, iterable){ if(iterable != undefined)forOf(iterable, isMap, that[ADDER], that); return that; } function fixSVZ(key, chain){ var method = proto[key]; if(framework)proto[key] = function(a, b){ var result = method.call(this, a === 0 ? 0 : a, b); return chain ? this : result; }; } if(!isNative(C) || !(isWeak || (!BUGGY_ITERATORS && has(proto, FOR_EACH) && has(proto, 'entries')))){ // create collection constructor C = isWeak ? function(iterable){ assertInstance(this, C, NAME); set(this, UID, uid++); initFromIterable(this, iterable); } : function(iterable){ var that = this; assertInstance(that, C, NAME); set(that, O1, create(null)); set(that, SIZE, 0); set(that, LAST, undefined); set(that, FIRST, undefined); initFromIterable(that, iterable); }; assignHidden(assignHidden(C[PROTOTYPE], methods), commonMethods); isWeak || !DESC || defineProperty(C[PROTOTYPE], 'size', {get: function(){ return assertDefined(this[SIZE]); }}); } else { var Native = C , inst = new C , chain = inst[ADDER](isWeak ? {} : -0, 1) , buggyZero; // wrap to init collections from iterable if(checkDangerIterClosing(function(O){ new C(O) })){ C = function(iterable){ assertInstance(this, C, NAME); return initFromIterable(new Native, iterable); } C[PROTOTYPE] = proto; if(framework)proto[CONSTRUCTOR] = C; } isWeak || inst[FOR_EACH](function(val, key){ buggyZero = 1 / key === -Infinity; }); // fix converting -0 key to +0 if(buggyZero){ fixSVZ('delete'); fixSVZ('has'); isMap && fixSVZ('get'); } // + fix .add & .set for chaining if(buggyZero || chain !== inst)fixSVZ(ADDER, true); } setToStringTag(C, NAME); setSpecies(C); O[NAME] = C; $define(GLOBAL + WRAP + FORCED * !isNative(C), O); // add .keys, .values, .entries, [@@iterator] // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 isWeak || defineStdIterators(C, NAME, function(iterated, kind){ set(this, ITER, {o: iterated, k: kind}); }, function(){ var iter = this[ITER] , kind = iter.k , entry = iter.l; // revert to the last existing entry while(entry && entry.r)entry = entry.p; // get next entry if(!iter.o || !(iter.l = entry = entry ? entry.n : iter.o[FIRST])){ // or finish the iteration iter.o = undefined; return iterResult(1); } // return step by kind if(kind == KEY) return iterResult(0, entry.k); if(kind == VALUE)return iterResult(0, entry.v); return iterResult(0, [entry.k, entry.v]); }, isMap ? KEY+VALUE : VALUE, !isMap); return C; } function fastKey(it, create){ // return primitive with prefix if(!isObject(it))return (typeof it == 'string' ? 'S' : 'P') + it; // can't set id to frozen object if(isFrozen(it))return 'F'; if(!has(it, UID)){ // not necessary to add id if(!create)return 'E'; // add missing object id hidden(it, UID, ++uid); // return object id with prefix } return 'O' + it[UID]; } function getEntry(that, key){ // fast case var index = fastKey(key), entry; if(index != 'F')return that[O1][index]; // frozen object case for(entry = that[FIRST]; entry; entry = entry.n){ if(entry.k == key)return entry; } } function def(that, key, value){ var entry = getEntry(that, key) , prev, index; // change existing entry if(entry)entry.v = value; // create new entry else { that[LAST] = entry = { i: index = fastKey(key, true), // <- index k: key, // <- key v: value, // <- value p: prev = that[LAST], // <- previous entry n: undefined, // <- next entry r: false // <- removed }; if(!that[FIRST])that[FIRST] = entry; if(prev)prev.n = entry; that[SIZE]++; // add to index if(index != 'F')that[O1][index] = entry; } return that; } var collectionMethods = { // 23.1.3.1 Map.prototype.clear() // 23.2.3.2 Set.prototype.clear() clear: function(){ for(var that = this, data = that[O1], entry = that[FIRST]; entry; entry = entry.n){ entry.r = true; if(entry.p)entry.p = entry.p.n = undefined; delete data[entry.i]; } that[FIRST] = that[LAST] = undefined; that[SIZE] = 0; }, // 23.1.3.3 Map.prototype.delete(key) // 23.2.3.4 Set.prototype.delete(value) 'delete': function(key){ var that = this , entry = getEntry(that, key); if(entry){ var next = entry.n , prev = entry.p; delete that[O1][entry.i]; entry.r = true; if(prev)prev.n = next; if(next)next.p = prev; if(that[FIRST] == entry)that[FIRST] = next; if(that[LAST] == entry)that[LAST] = prev; that[SIZE]--; } return !!entry; }, // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) forEach: function(callbackfn /*, that = undefined */){ var f = ctx(callbackfn, arguments[1], 3) , entry; while(entry = entry ? entry.n : this[FIRST]){ f(entry.v, entry.k, this); // revert to the last existing entry while(entry && entry.r)entry = entry.p; } }, // 23.1.3.7 Map.prototype.has(key) // 23.2.3.7 Set.prototype.has(value) has: function(key){ return !!getEntry(this, key); } } // 23.1 Map Objects Map = getCollection(Map, MAP, { // 23.1.3.6 Map.prototype.get(key) get: function(key){ var entry = getEntry(this, key); return entry && entry.v; }, // 23.1.3.9 Map.prototype.set(key, value) set: function(key, value){ return def(this, key === 0 ? 0 : key, value); } }, collectionMethods, true); // 23.2 Set Objects Set = getCollection(Set, SET, { // 23.2.3.1 Set.prototype.add(value) add: function(value){ return def(this, value = value === 0 ? 0 : value, value); } }, collectionMethods); function defWeak(that, key, value){ if(isFrozen(assertObject(key)))leakStore(that).set(key, value); else { has(key, WEAK) || hidden(key, WEAK, {}); key[WEAK][that[UID]] = value; } return that; } function leakStore(that){ return that[LEAK] || hidden(that, LEAK, new Map)[LEAK]; } var weakMethods = { // 23.3.3.2 WeakMap.prototype.delete(key) // 23.4.3.3 WeakSet.prototype.delete(value) 'delete': function(key){ if(!isObject(key))return false; if(isFrozen(key))return leakStore(this)['delete'](key); return has(key, WEAK) && has(key[WEAK], this[UID]) && delete key[WEAK][this[UID]]; }, // 23.3.3.4 WeakMap.prototype.has(key) // 23.4.3.4 WeakSet.prototype.has(value) has: function(key){ if(!isObject(key))return false; if(isFrozen(key))return leakStore(this).has(key); return has(key, WEAK) && has(key[WEAK], this[UID]); } }; // 23.3 WeakMap Objects WeakMap = getCollection(WeakMap, WEAKMAP, { // 23.3.3.3 WeakMap.prototype.get(key) get: function(key){ if(isObject(key)){ if(isFrozen(key))return leakStore(this).get(key); if(has(key, WEAK))return key[WEAK][this[UID]]; } }, // 23.3.3.5 WeakMap.prototype.set(key, value) set: function(key, value){ return defWeak(this, key, value); } }, weakMethods, true, true); // IE11 WeakMap frozen keys fix if(framework && new WeakMap().set(Object.freeze(tmp), 7).get(tmp) != 7){ forEach.call(array('delete,has,get,set'), function(key){ var method = WeakMap[PROTOTYPE][key]; WeakMap[PROTOTYPE][key] = function(a, b){ // store frozen objects on leaky map if(isObject(a) && isFrozen(a)){ var result = leakStore(this)[key](a, b); return key == 'set' ? this : result; // store all the rest on native weakmap } return method.call(this, a, b); }; }); } // 23.4 WeakSet Objects WeakSet = getCollection(WeakSet, WEAKSET, { // 23.4.3.1 WeakSet.prototype.add(value) add: function(value){ return defWeak(this, value, true); } }, weakMethods, false, true); }(); /****************************************************************************** * Module : es6.reflect * ******************************************************************************/ !function(){ function Enumerate(iterated){ var keys = [], key; for(key in iterated)keys.push(key); set(this, ITER, {o: iterated, a: keys, i: 0}); } createIterator(Enumerate, OBJECT, function(){ var iter = this[ITER] , keys = iter.a , key; do { if(iter.i >= keys.length)return iterResult(1); } while(!((key = keys[iter.i++]) in iter.o)); return iterResult(0, key); }); function wrap(fn){ return function(it){ assertObject(it); try { return fn.apply(undefined, arguments), true; } catch(e){ return false; } } } function reflectGet(target, propertyKey/*, receiver*/){ var receiver = arguments.length < 3 ? target : arguments[2] , desc = getOwnDescriptor(assertObject(target), propertyKey), proto; if(desc)return has(desc, 'value') ? desc.value : desc.get === undefined ? undefined : desc.get.call(receiver); return isObject(proto = getPrototypeOf(target)) ? reflectGet(proto, propertyKey, receiver) : undefined; } function reflectSet(target, propertyKey, V/*, receiver*/){ var receiver = arguments.length < 4 ? target : arguments[3] , ownDesc = getOwnDescriptor(assertObject(target), propertyKey) , existingDescriptor, proto; if(!ownDesc){ if(isObject(proto = getPrototypeOf(target))){ return reflectSet(proto, propertyKey, V, receiver); } ownDesc = descriptor(0); } if(has(ownDesc, 'value')){ if(ownDesc.writable === false || !isObject(receiver))return false; existingDescriptor = getOwnDescriptor(receiver, propertyKey) || descriptor(0); existingDescriptor.value = V; return defineProperty(receiver, propertyKey, existingDescriptor), true; } return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true); } var isExtensible = Object.isExtensible || returnIt; var reflect = { // 26.1.1 Reflect.apply(target, thisArgument, argumentsList) apply: ctx(call, apply, 3), // 26.1.2 Reflect.construct(target, argumentsList [, newTarget]) construct: function(target, argumentsList /*, newTarget*/){ var proto = assertFunction(arguments.length < 3 ? target : arguments[2])[PROTOTYPE] , instance = create(isObject(proto) ? proto : ObjectProto) , result = apply.call(target, instance, argumentsList); return isObject(result) ? result : instance; }, // 26.1.3 Reflect.defineProperty(target, propertyKey, attributes) defineProperty: wrap(defineProperty), // 26.1.4 Reflect.deleteProperty(target, propertyKey) deleteProperty: function(target, propertyKey){ var desc = getOwnDescriptor(assertObject(target), propertyKey); return desc && !desc.configurable ? false : delete target[propertyKey]; }, // 26.1.5 Reflect.enumerate(target) enumerate: function(target){ return new Enumerate(assertObject(target)); }, // 26.1.6 Reflect.get(target, propertyKey [, receiver]) get: reflectGet, // 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey) getOwnPropertyDescriptor: function(target, propertyKey){ return getOwnDescriptor(assertObject(target), propertyKey); }, // 26.1.8 Reflect.getPrototypeOf(target) getPrototypeOf: function(target){ return getPrototypeOf(assertObject(target)); }, // 26.1.9 Reflect.has(target, propertyKey) has: function(target, propertyKey){ return propertyKey in target; }, // 26.1.10 Reflect.isExtensible(target) isExtensible: function(target){ return !!isExtensible(assertObject(target)); }, // 26.1.11 Reflect.ownKeys(target) ownKeys: ownKeys, // 26.1.12 Reflect.preventExtensions(target) preventExtensions: wrap(Object.preventExtensions || returnIt), // 26.1.13 Reflect.set(target, propertyKey, V [, receiver]) set: reflectSet } // 26.1.14 Reflect.setPrototypeOf(target, proto) if(setPrototypeOf)reflect.setPrototypeOf = function(target, proto){ return setPrototypeOf(assertObject(target), proto), true; }; $define(GLOBAL, {Reflect: {}}); $define(STATIC, 'Reflect', reflect); }(); /****************************************************************************** * Module : es7.proposals * ******************************************************************************/ !function(){ $define(PROTO, ARRAY, { // https://github.com/domenic/Array.prototype.includes includes: createArrayContains(true) }); $define(PROTO, STRING, { // https://github.com/mathiasbynens/String.prototype.at at: createPointAt(true) }); function createObjectToArray(isEntries){ return function(object){ var O = toObject(object) , keys = getKeys(object) , length = keys.length , i = 0 , result = Array(length) , key; if(isEntries)while(length > i)result[i] = [key = keys[i++], O[key]]; else while(length > i)result[i] = O[keys[i++]]; return result; } } $define(STATIC, OBJECT, { // https://gist.github.com/WebReflection/9353781 getOwnPropertyDescriptors: function(object){ var O = toObject(object) , result = {}; forEach.call(ownKeys(O), function(key){ defineProperty(result, key, descriptor(0, getOwnDescriptor(O, key))); }); return result; }, // https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-04/apr-9.md#51-objectentries-objectvalues values: createObjectToArray(false), entries: createObjectToArray(true) }); $define(STATIC, REGEXP, { // https://gist.github.com/kangax/9698100 escape: createReplacer(/([\\\-[\]{}()*+?.,^$|])/g, '\\$1', true) }); }(); /****************************************************************************** * Module : es7.abstract-refs * ******************************************************************************/ // https://github.com/zenparsing/es-abstract-refs !function(REFERENCE){ REFERENCE_GET = getWellKnownSymbol(REFERENCE+'Get', true); var REFERENCE_SET = getWellKnownSymbol(REFERENCE+SET, true) , REFERENCE_DELETE = getWellKnownSymbol(REFERENCE+'Delete', true); $define(STATIC, SYMBOL, { referenceGet: REFERENCE_GET, referenceSet: REFERENCE_SET, referenceDelete: REFERENCE_DELETE }); hidden(FunctionProto, REFERENCE_GET, returnThis); function setMapMethods(Constructor){ if(Constructor){ var MapProto = Constructor[PROTOTYPE]; hidden(MapProto, REFERENCE_GET, MapProto.get); hidden(MapProto, REFERENCE_SET, MapProto.set); hidden(MapProto, REFERENCE_DELETE, MapProto['delete']); } } setMapMethods(Map); setMapMethods(WeakMap); }('reference'); /****************************************************************************** * Module : core.dict * ******************************************************************************/ !function(DICT){ Dict = function(iterable){ var dict = create(null); if(iterable != undefined){ if(isIterable(iterable)){ forOf(iterable, true, function(key, value){ dict[key] = value; }); } else assign(dict, iterable); } return dict; } Dict[PROTOTYPE] = null; function DictIterator(iterated, kind){ set(this, ITER, {o: toObject(iterated), a: getKeys(iterated), i: 0, k: kind}); } createIterator(DictIterator, DICT, function(){ var iter = this[ITER] , O = iter.o , keys = iter.a , kind = iter.k , key; do { if(iter.i >= keys.length){ iter.o = undefined; return iterResult(1); } } while(!has(O, key = keys[iter.i++])); if(kind == KEY) return iterResult(0, key); if(kind == VALUE)return iterResult(0, O[key]); return iterResult(0, [key, O[key]]); }); function createDictIter(kind){ return function(it){ return new DictIterator(it, kind); } } /* * 0 -> forEach * 1 -> map * 2 -> filter * 3 -> some * 4 -> every * 5 -> find * 6 -> findKey * 7 -> mapPairs */ function createDictMethod(type){ var isMap = type == 1 , isEvery = type == 4; return function(object, callbackfn, that /* = undefined */){ var f = ctx(callbackfn, that, 3) , O = toObject(object) , result = isMap || type == 7 || type == 2 ? new (generic(this, Dict)) : undefined , key, val, res; for(key in O)if(has(O, key)){ val = O[key]; res = f(val, key, object); if(type){ if(isMap)result[key] = res; // map else if(res)switch(type){ case 2: result[key] = val; break // filter case 3: return true; // some case 5: return val; // find case 6: return key; // findKey case 7: result[res[0]] = res[1]; // mapPairs } else if(isEvery)return false; // every } } return type == 3 || isEvery ? isEvery : result; } } function createDictReduce(isTurn){ return function(object, mapfn, init){ assertFunction(mapfn); var O = toObject(object) , keys = getKeys(O) , length = keys.length , i = 0 , memo, key, result; if(isTurn)memo = init == undefined ? new (generic(this, Dict)) : Object(init); else if(arguments.length < 3){ assert(length, REDUCE_ERROR); memo = O[keys[i++]]; } else memo = Object(init); while(length > i)if(has(O, key = keys[i++])){ result = mapfn(memo, O[key], key, object); if(isTurn){ if(result === false)break; } else memo = result; } return memo; } } var findKey = createDictMethod(6); function includes(object, el){ return (el == el ? keyOf(object, el) : findKey(object, sameNaN)) !== undefined; } var dictMethods = { keys: createDictIter(KEY), values: createDictIter(VALUE), entries: createDictIter(KEY+VALUE), forEach: createDictMethod(0), map: createDictMethod(1), filter: createDictMethod(2), some: createDictMethod(3), every: createDictMethod(4), find: createDictMethod(5), findKey: findKey, mapPairs:createDictMethod(7), reduce: createDictReduce(false), turn: createDictReduce(true), keyOf: keyOf, includes:includes, // Has / get / set own property has: has, get: get, set: createDefiner(0), isDict: function(it){ return isObject(it) && getPrototypeOf(it) === Dict[PROTOTYPE]; } }; if(REFERENCE_GET)for(var key in dictMethods)!function(fn){ function method(){ for(var args = [this], i = 0; i < arguments.length;)args.push(arguments[i++]); return invoke(fn, args); } fn[REFERENCE_GET] = function(){ return method; } }(dictMethods[key]); $define(GLOBAL + FORCED, {Dict: assignHidden(Dict, dictMethods)}); }('Dict'); /****************************************************************************** * Module : core.$for * ******************************************************************************/ !function(ENTRIES, FN){ function $for(iterable, entries){ if(!(this instanceof $for))return new $for(iterable, entries); this[ITER] = getIterator(iterable); this[ENTRIES] = !!entries; } createIterator($for, 'Wrapper', function(){ return this[ITER].next(); }); var $forProto = $for[PROTOTYPE]; setIterator($forProto, function(){ return this[ITER]; // unwrap }); function createChainIterator(next){ function Iter(I, fn, that){ this[ITER] = getIterator(I); this[ENTRIES] = I[ENTRIES]; this[FN] = ctx(fn, that, I[ENTRIES] ? 2 : 1); } createIterator(Iter, 'Chain', next, $forProto); setIterator(Iter[PROTOTYPE], returnThis); // override $forProto iterator return Iter; } var MapIter = createChainIterator(function(){ var step = this[ITER].next(); return step.done ? step : iterResult(0, stepCall(this[FN], step.value, this[ENTRIES])); }); var FilterIter = createChainIterator(function(){ for(;;){ var step = this[ITER].next(); if(step.done || stepCall(this[FN], step.value, this[ENTRIES]))return step; } }); assignHidden($forProto, { of: function(fn, that){ forOf(this, this[ENTRIES], fn, that); }, array: function(fn, that){ var result = []; forOf(fn != undefined ? this.map(fn, that) : this, false, push, result); return result; }, filter: function(fn, that){ return new FilterIter(this, fn, that); }, map: function(fn, that){ return new MapIter(this, fn, that); } }); $for.isIterable = isIterable; $for.getIterator = getIterator; $define(GLOBAL + FORCED, {$for: $for}); }('entries', safeSymbol('fn')); /****************************************************************************** * Module : core.delay * ******************************************************************************/ // https://esdiscuss.org/topic/promise-returning-delay-function $define(GLOBAL + FORCED, { delay: function(time){ return new Promise(function(resolve){ setTimeout(resolve, time, true); }); } }); /****************************************************************************** * Module : core.binding * ******************************************************************************/ !function(_, toLocaleString){ // Placeholder core._ = path._ = path._ || {}; $define(PROTO + FORCED, FUNCTION, { part: part, only: function(numberArguments, that /* = @ */){ var fn = assertFunction(this) , n = toLength(numberArguments) , isThat = arguments.length > 1; return function(/* ...args */){ var length = min(n, arguments.length) , args = Array(length) , i = 0; while(length > i)args[i] = arguments[i++]; return invoke(fn, args, isThat ? that : this); } } }); function tie(key){ var that = this , bound = {}; return hidden(that, _, function(key){ if(key === undefined || !(key in that))return toLocaleString.call(that); return has(bound, key) ? bound[key] : (bound[key] = ctx(that[key], that, -1)); })[_](key); } hidden(path._, TO_STRING, function(){ return _; }); hidden(ObjectProto, _, tie); DESC || hidden(ArrayProto, _, tie); // IE8- dirty hack - redefined toLocaleString is not enumerable }(DESC ? uid('tie') : TO_LOCALE, ObjectProto[TO_LOCALE]); /****************************************************************************** * Module : core.object * ******************************************************************************/ !function(){ function define(target, mixin){ var keys = ownKeys(toObject(mixin)) , length = keys.length , i = 0, key; while(length > i)defineProperty(target, key = keys[i++], getOwnDescriptor(mixin, key)); return target; }; $define(STATIC + FORCED, OBJECT, { isObject: isObject, classof: classof, define: define, make: function(proto, mixin){ return define(create(proto), mixin); } }); }(); /****************************************************************************** * Module : core.array * ******************************************************************************/ $define(PROTO + FORCED, ARRAY, { turn: function(fn, target /* = [] */){ assertFunction(fn); var memo = target == undefined ? [] : Object(target) , O = ES5Object(this) , length = toLength(O.length) , index = 0; while(length > index)if(fn(memo, O[index], index++, this) === false)break; return memo; } }); if(framework)ArrayUnscopables.turn = true; /****************************************************************************** * Module : core.number * ******************************************************************************/ !function(numberMethods){ function NumberIterator(iterated){ set(this, ITER, {l: toLength(iterated), i: 0}); } createIterator(NumberIterator, NUMBER, function(){ var iter = this[ITER] , i = iter.i++; return i < iter.l ? iterResult(0, i) : iterResult(1); }); defineIterator(Number, NUMBER, function(){ return new NumberIterator(this); }); numberMethods.random = function(lim /* = 0 */){ var a = +this , b = lim == undefined ? 0 : +lim , m = min(a, b); return random() * (max(a, b) - m) + m; }; forEach.call(array( // ES3: 'round,floor,ceil,abs,sin,asin,cos,acos,tan,atan,exp,sqrt,max,min,pow,atan2,' + // ES6: 'acosh,asinh,atanh,cbrt,clz32,cosh,expm1,hypot,imul,log1p,log10,log2,sign,sinh,tanh,trunc' ), function(key){ var fn = Math[key]; if(fn)numberMethods[key] = function(/* ...args */){ // ie9- dont support strict mode & convert `this` to object -> convert it to number var args = [+this] , i = 0; while(arguments.length > i)args.push(arguments[i++]); return invoke(fn, args); } } ); $define(PROTO + FORCED, NUMBER, numberMethods); }({}); /****************************************************************************** * Module : core.string * ******************************************************************************/ !function(){ var escapeHTMLDict = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;' }, unescapeHTMLDict = {}, key; for(key in escapeHTMLDict)unescapeHTMLDict[escapeHTMLDict[key]] = key; $define(PROTO + FORCED, STRING, { escapeHTML: createReplacer(/[&<>"']/g, escapeHTMLDict), unescapeHTML: createReplacer(/&(?:amp|lt|gt|quot|apos);/g, unescapeHTMLDict) }); }(); /****************************************************************************** * Module : core.date * ******************************************************************************/ !function(formatRegExp, flexioRegExp, locales, current, SECONDS, MINUTES, HOURS, MONTH, YEAR){ function createFormat(prefix){ return function(template, locale /* = current */){ var that = this , dict = locales[has(locales, locale) ? locale : current]; function get(unit){ return that[prefix + unit](); } return String(template).replace(formatRegExp, function(part){ switch(part){ case 's' : return get(SECONDS); // Seconds : 0-59 case 'ss' : return lz(get(SECONDS)); // Seconds : 00-59 case 'm' : return get(MINUTES); // Minutes : 0-59 case 'mm' : return lz(get(MINUTES)); // Minutes : 00-59 case 'h' : return get(HOURS); // Hours : 0-23 case 'hh' : return lz(get(HOURS)); // Hours : 00-23 case 'D' : return get(DATE); // Date : 1-31 case 'DD' : return lz(get(DATE)); // Date : 01-31 case 'W' : return dict[0][get('Day')]; // Day : Понедельник case 'N' : return get(MONTH) + 1; // Month : 1-12 case 'NN' : return lz(get(MONTH) + 1); // Month : 01-12 case 'M' : return dict[2][get(MONTH)]; // Month : Январь case 'MM' : return dict[1][get(MONTH)]; // Month : Января case 'Y' : return get(YEAR); // Year : 2014 case 'YY' : return lz(get(YEAR) % 100); // Year : 14 } return part; }); } } function addLocale(lang, locale){ function split(index){ var result = []; forEach.call(array(locale.months), function(it){ result.push(it.replace(flexioRegExp, '$' + index)); }); return result; } locales[lang] = [array(locale.weekdays), split(1), split(2)]; return core; } $define(PROTO + FORCED, DATE, { format: createFormat('get'), formatUTC: createFormat('getUTC') }); addLocale(current, { weekdays: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday', months: 'January,February,March,April,May,June,July,August,September,October,November,December' }); addLocale('ru', { weekdays: 'Воскресенье,Понедельник,Вторник,Среда,Четверг,Пятница,Суббота', months: 'Январ:я|ь,Феврал:я|ь,Март:а|,Апрел:я|ь,Ма:я|й,Июн:я|ь,' + 'Июл:я|ь,Август:а|,Сентябр:я|ь,Октябр:я|ь,Ноябр:я|ь,Декабр:я|ь' }); core.locale = function(locale){ return has(locales, locale) ? current = locale : current; }; core.addLocale = addLocale; }(/\b\w\w?\b/g, /:(.*)\|(.*)$/, {}, 'en', 'Seconds', 'Minutes', 'Hours', 'Month', 'FullYear'); /****************************************************************************** * Module : core.global * ******************************************************************************/ $define(GLOBAL + FORCED, {global: global}); /****************************************************************************** * Module : js.array.statics * ******************************************************************************/ // JavaScript 1.6 / Strawman array statics shim !function(arrayStatics){ function setArrayStatics(keys, length){ forEach.call(array(keys), function(key){ if(key in ArrayProto)arrayStatics[key] = ctx(call, ArrayProto[key], length); }); } setArrayStatics('pop,reverse,shift,keys,values,entries', 1); setArrayStatics('indexOf,every,some,forEach,map,filter,find,findIndex,includes', 3); setArrayStatics('join,slice,concat,push,splice,unshift,sort,lastIndexOf,' + 'reduce,reduceRight,copyWithin,fill,turn'); $define(STATIC, ARRAY, arrayStatics); }({}); /****************************************************************************** * Module : web.dom.itarable * ******************************************************************************/ !function(NodeList){ if(framework && NodeList && !(SYMBOL_ITERATOR in NodeList[PROTOTYPE])){ hidden(NodeList[PROTOTYPE], SYMBOL_ITERATOR, Iterators[ARRAY]); } Iterators.NodeList = Iterators[ARRAY]; }(global.NodeList); /****************************************************************************** * Module : core.log * ******************************************************************************/ !function(log, enabled){ // Methods from https://github.com/DeveloperToolsWG/console-object/blob/master/api.md forEach.call(array('assert,clear,count,debug,dir,dirxml,error,exception,' + 'group,groupCollapsed,groupEnd,info,isIndependentlyComposed,log,' + 'markTimeline,profile,profileEnd,table,time,timeEnd,timeline,' + 'timelineEnd,timeStamp,trace,warn'), function(key){ log[key] = function(){ if(enabled && key in console)return apply.call(console[key], console, arguments); }; }); $define(GLOBAL + FORCED, {log: assign(log.log, log, { enable: function(){ enabled = true; }, disable: function(){ enabled = false; } })}); }({}, true); }(typeof self != 'undefined' && self.Math === Math ? self : Function('return this')(), true);
ajax/libs/jquery/1.10.0/jquery.js
Mrkebubun/cdnjs
/*! * jQuery JavaScript Library v1.10.0 * 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-05-24T18:39Z */ (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.0", // 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.9.4-pre * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-05-15 */ (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() { 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 ); } /** * For feature detection * @param {Function} fn The function to test for native support */ function isNative( fn ) { return rnative.test( fn + "" ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var 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 if the test fails * @param {Boolean} test The result of a test. If true, null will be set as the handler in leiu of the specified handler */ function addHandle( attrs, handler, test ) { attrs = attrs.split("|"); var current, i = attrs.length, setHandle = test ? null : handler; while ( i-- ) { // Don't override a user's handler if ( !(current = Expr.attrHandle[ attrs[i] ]) || current === handler ) { Expr.attrHandle[ attrs[i] ] = setHandle; } } } /** * Fetches boolean attributes by node * @param {Element} elem * @param {String} name */ function boolHandler( elem, name ) { // XML does not need to be checked as this will not be assigned for XML documents var val = elem.getAttributeNode( name ); return val && val.specified ? val.value : elem[ name ] === true ? name.toLowerCase() : null; } /** * Fetches attributes without interpolation * http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx * @param {Element} elem * @param {String} name */ function interpolationHandler( elem, name ) { // XML does not need to be checked as this will not be assigned for XML documents return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } /** * Uses defaultValue to retrieve value in IE6/7 * @param {Element} elem * @param {String} name */ function valueHandler( elem ) { // Ignore the value *property* on inputs by using defaultValue // Fallback to Sizzle.attr by returning undefined where appropriate // XML does not need to be checked as this will not be assigned for XML documents if ( elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns Returns -1 if a precedes b, 1 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; // 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 ); /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { // Support: IE<8 // Prevent attribute/property "interpolation" div.innerHTML = "<a href='#'></a>"; addHandle( "type|href|height|width", interpolationHandler, div.firstChild.getAttribute("href") === "#" ); // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies addHandle( booleans, boolHandler, div.getAttribute("disabled") == null ); div.className = "i"; return !div.getAttribute("className"); }); // Support: IE<9 // Retrieving value should defer to defaultValue support.input = assert(function( div ) { div.innerHTML = "<input>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }); // IE6/7 still return empty string for value, // but are actually retrieving the property addHandle( "value", valueHandler, support.attributes && support.input ); /* 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 = isNative(doc.querySelectorAll)) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not 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 = isNative( (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 = isNative(docElem.contains) || docElem.compareDocumentPosition ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // 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( doc.createElement("div") ) & 1; }); // 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; }) } }; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var data, cache, outerCache, dirkey = dirruns + " " + doneName; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // 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; } // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Initialize against the default document setDocument(); // Support: Chrome<<14 // Always assume duplicates if they aren't passed to the comparison function [0, 0].sort( sortOrder ); support.detectDuplicates = hasDuplicate; 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 ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( list && ( !fired || stack ) ) { if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function( 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--; } hooks.cur = fn; if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery._removeData( elem, type + "queue" ); jQuery._removeData( elem, key ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, rclass = /[\t\r\n\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, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.match( core_rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } // Toggle whole class name } else if ( type === core_strundefined || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var ret, hooks, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; 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 ) { var bool = typeof state === "boolean"; return this.each(function() { if ( bool ? state : isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var num, val, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); // 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 ) { tween.unit = unit; tween.start = +start || +target || 0; // 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 ); doAnimation.finish = function() { anim.stop( true ); }; // Empty animations, or finishing resolves immediately if ( empty || jQuery._data( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = jQuery._data( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // enable finishing flag on private data data.finish = true; // empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.cur && hooks.cur.finish ) { hooks.cur.finish.call( this ); } // look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // turn off finishing flag delete data.finish; }); } }); // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth? 1 : 0; for( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p*Math.PI ) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { if ( timer() && jQuery.timers.push( timer ) ) { jQuery.fx.start(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== core_strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ), left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 ) }; }; jQuery.offset = { setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, parentOffset = { top: 0, left: 0 }, elem = this[ 0 ]; // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // we assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || 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" && typeof module.exports === "object" ) { // Expose jQuery as module.exports in loaders that implement the Node // module pattern (including browserify). Do not create the global, since // the user will be storing it themselves locally, and globals are frowned // upon in the Node module world. module.exports = jQuery; } else { // Otherwise expose jQuery to the global object as usual window.jQuery = window.$ = jQuery; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd ) { define( "jquery", [], function () { return jQuery; } ); } } })( window );
packages/material-ui-icons/src/SkipPreviousSharp.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M6 6h2v12H6V6zm3.5 6l8.5 6V6l-8.5 6z" /> , 'SkipPreviousSharp');
src/svg-icons/action/zoom-in.js
rscnt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionZoomIn = (props) => ( <SvgIcon {...props}> <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14zm2.5-4h-2v2H9v-2H7V9h2V7h1v2h2v1z"/> </SvgIcon> ); ActionZoomIn = pure(ActionZoomIn); ActionZoomIn.displayName = 'ActionZoomIn'; export default ActionZoomIn;
packages/material-ui/src/Portal/LegacyPortal.js
cherniavskii/material-ui
import React from 'react'; import ReactDOM from 'react-dom'; import PropTypes from 'prop-types'; import ownerDocument from 'dom-helpers/ownerDocument'; import exactProp from '../utils/exactProp'; function getContainer(container, defaultContainer) { container = typeof container === 'function' ? container() : container; return ReactDOM.findDOMNode(container) || defaultContainer; } function getOwnerDocument(element) { return ownerDocument(ReactDOM.findDOMNode(element)); } /** * @ignore - internal component. * * This module will soon be gone. We should drop it as soon as [email protected] support stop. */ class LegacyPortal extends React.Component { componentDidMount() { this.mounted = true; this.renderOverlay(); } componentDidUpdate(prevProps) { if (this.overlayTarget && prevProps.container !== this.props.container) { this.mountNode.removeChild(this.overlayTarget); this.mountNode = getContainer(this.props.container, getOwnerDocument(this).body); this.mountNode.appendChild(this.overlayTarget); } this.renderOverlay(); } componentWillUnmount() { this.mounted = false; this.unrenderOverlay(); this.unmountOverlayTarget(); } /** * @public */ getMountNode = () => { return this.mountNode; }; mountOverlayTarget = () => { if (!this.overlayTarget) { this.overlayTarget = document.createElement('div'); this.mountNode = getContainer(this.props.container, getOwnerDocument(this).body); this.mountNode.appendChild(this.overlayTarget); } }; unmountOverlayTarget = () => { if (this.overlayTarget) { this.mountNode.removeChild(this.overlayTarget); this.overlayTarget = null; } this.mountNode = null; }; unrenderOverlay = () => { if (this.overlayTarget) { ReactDOM.unmountComponentAtNode(this.overlayTarget); this.overlayInstance = null; } }; renderOverlay = () => { const overlay = this.props.children; this.mountOverlayTarget(); const initialRender = !this.overlayInstance; this.overlayInstance = ReactDOM.unstable_renderSubtreeIntoContainer( this, overlay, this.overlayTarget, () => { if (initialRender && this.props.onRendered) { this.props.onRendered(); } }, ); }; render() { return null; } } LegacyPortal.propTypes = { children: PropTypes.element.isRequired, container: PropTypes.oneOfType([PropTypes.object, PropTypes.func]), onRendered: PropTypes.func, }; LegacyPortal.propTypes = exactProp(LegacyPortal.propTypes, 'LegacyPortal'); export default LegacyPortal;
code/workspaces/web-app/src/components/modal/RobustConfirmation.spec.js
NERC-CEH/datalab
import React from 'react'; import { shallow } from 'enzyme'; import TextField from '@material-ui/core/TextField'; import RobustConfirmation from './RobustConfirmation'; import SecondaryActionButton from '../common/buttons/SecondaryActionButton'; import DangerButton from '../common/buttons/DangerButton'; function shallowRender(props) { return shallow(<RobustConfirmation {...props} />); } describe('Robust Confirmation', () => { const onSubmitMock = jest.fn(); const onCancelMock = jest.fn(); const generateProps = () => ({ title: 'Title', body: 'Body', confirmField: { label: 'FieldLabel', expectedValue: 'alpha', }, onSubmit: onSubmitMock, onCancel: onCancelMock, }); beforeEach(() => jest.resetAllMocks()); it('creates correct snapshot for confirmation dialog', () => { // Arrange const props = generateProps(); // Act const output = shallowRender(props); // Assert expect(output).toMatchSnapshot(); }); it('wires up cancel function correctly', () => { // Arrange const props = generateProps(); // Act const output = shallowRender(props); const buttons = output.find(SecondaryActionButton); const cancelFunction = buttons.find({ children: 'Cancel' }).prop('onClick'); cancelFunction(); // Assert expect(onCancelMock).toHaveBeenCalled(); }); it('wires up submit function correctly', () => { // Arrange const props = generateProps(); // Act const output = shallowRender(props); const buttons = output.find(DangerButton); const submitFunction = buttons.find({ children: 'Delete' }).prop('onClick'); submitFunction(); // Assert expect(onSubmitMock).toHaveBeenCalled(); }); it('submit button is enable when TextField contains expected value', () => { // Arrange const props = generateProps(); // Act const output = shallowRender(props); const textOnChange = output.find(TextField).prop('onChange'); // Assert // Due to changes state, for this test, the same node need to be used for the expect checks. expect(output.find(DangerButton).find({ children: 'Delete' }).prop('disabled')).toBe(true); textOnChange({ target: { value: 'alpha' } }); expect(output.find(DangerButton).find({ children: 'Delete' }).prop('disabled')).toBe(false); }); });
examples/Modal.js
15lyfromsaturn/react-materialize
import React from 'react'; import Modal from '../src/Modal'; import Button from '../src/Button'; export default <Modal header='Modal Header' trigger={ <Button waves='light'>MODAL</Button> }> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p> </Modal>;
ajax/libs/react-bootstrap-table/2.0.3/react-bootstrap-table.js
tholu/cdnjs
(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["ReactBootstrapTable"] = factory(require("react"), require("react-dom")); else root["ReactBootstrapTable"] = factory(root["React"], root["ReactDOM"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_2__, __WEBPACK_EXTERNAL_MODULE_5__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _BootstrapTable = __webpack_require__(1); var _BootstrapTable2 = _interopRequireDefault(_BootstrapTable); var _TableHeaderColumn = __webpack_require__(41); var _TableHeaderColumn2 = _interopRequireDefault(_TableHeaderColumn); var _storeTableDataStore = __webpack_require__(33); if (typeof window !== 'undefined') { window.BootstrapTable = _BootstrapTable2['default']; window.TableHeaderColumn = _TableHeaderColumn2['default']; window.TableDataSet = _storeTableDataStore.TableDataSet; } exports.BootstrapTable = _BootstrapTable2['default']; exports.TableHeaderColumn = _TableHeaderColumn2['default']; exports.TableDataSet = _storeTableDataStore.TableDataSet; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { /* eslint no-alert: 0 */ /* eslint max-len: 0 */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var _TableHeader = __webpack_require__(4); var _TableHeader2 = _interopRequireDefault(_TableHeader); var _TableBody = __webpack_require__(8); var _TableBody2 = _interopRequireDefault(_TableBody); var _paginationPaginationList = __webpack_require__(29); var _paginationPaginationList2 = _interopRequireDefault(_paginationPaginationList); var _toolbarToolBar = __webpack_require__(31); var _toolbarToolBar2 = _interopRequireDefault(_toolbarToolBar); var _TableFilter = __webpack_require__(32); var _TableFilter2 = _interopRequireDefault(_TableFilter); var _storeTableDataStore = __webpack_require__(33); var _util = __webpack_require__(35); var _util2 = _interopRequireDefault(_util); var _csv_export_util = __webpack_require__(36); var _csv_export_util2 = _interopRequireDefault(_csv_export_util); var _Filter = __webpack_require__(40); var BootstrapTable = (function (_Component) { _inherits(BootstrapTable, _Component); function BootstrapTable(props) { var _this = this; _classCallCheck(this, BootstrapTable); _get(Object.getPrototypeOf(BootstrapTable.prototype), 'constructor', this).call(this, props); this.handleSort = function (order, sortField) { if (_this.props.options.onSortChange) { _this.props.options.onSortChange(sortField, order, _this.props); } var result = _this.store.sort(order, sortField).get(); _this.setState({ data: result }); }; this.handlePaginationData = function (page, sizePerPage) { var onPageChange = _this.props.options.onPageChange; if (onPageChange) { onPageChange(page, sizePerPage); } if (_this.isRemoteDataSource()) { return; } var result = _this.store.page(page, sizePerPage).get(); _this.setState({ data: result, currPage: page, sizePerPage: sizePerPage }); }; this.handleMouseLeave = function () { if (_this.props.options.onMouseLeave) { _this.props.options.onMouseLeave(); } }; this.handleMouseEnter = function () { if (_this.props.options.onMouseEnter) { _this.props.options.onMouseEnter(); } }; this.handleRowMouseOut = function (row, event) { if (_this.props.options.onRowMouseOut) { _this.props.options.onRowMouseOut(row, event); } }; this.handleRowMouseOver = function (row, event) { if (_this.props.options.onRowMouseOver) { _this.props.options.onRowMouseOver(row, event); } }; this.handleRowClick = function (row) { if (_this.props.options.onRowClick) { _this.props.options.onRowClick(row); } }; this.handleSelectAllRow = function (e) { var isSelected = e.currentTarget.checked; var selectedRowKeys = []; var result = true; if (_this.props.selectRow.onSelectAll) { result = _this.props.selectRow.onSelectAll(isSelected, isSelected ? _this.store.get() : []); } if (typeof result === 'undefined' || result !== false) { if (isSelected) { selectedRowKeys = _this.store.getAllRowkey(); } _this.store.setSelectedRowKey(selectedRowKeys); _this.setState({ selectedRowKeys: selectedRowKeys }); } }; this.handleShowOnlySelected = function () { _this.store.ignoreNonSelected(); var result = undefined; if (_this.props.pagination) { result = _this.store.page(1, _this.state.sizePerPage).get(); } else { result = _this.store.get(); } _this.setState({ data: result, currPage: 1 }); }; this.handleSelectRow = function (row, isSelected) { var result = true; var currSelected = _this.store.getSelectedRowKeys(); var rowKey = row[_this.store.getKeyField()]; var selectRow = _this.props.selectRow; if (selectRow.onSelect) { result = selectRow.onSelect(row, isSelected); } if (typeof result === 'undefined' || result !== false) { if (selectRow.mode === _Const2['default'].ROW_SELECT_SINGLE) { currSelected = isSelected ? [rowKey] : []; } else { if (isSelected) { currSelected.push(rowKey); } else { currSelected = currSelected.filter(function (key) { return rowKey !== key; }); } } _this.store.setSelectedRowKey(currSelected); _this.setState({ selectedRowKeys: currSelected }); } }; this.handleAddRow = function (newObj) { try { _this.store.add(newObj); } catch (e) { return e; } _this._handleAfterAddingRow(newObj); }; this.handleDropRow = function (rowKeys) { var dropRowKeys = rowKeys ? rowKeys : _this.store.getSelectedRowKeys(); // add confirm before the delete action if that option is set. if (dropRowKeys && dropRowKeys.length > 0) { if (_this.props.options.handleConfirmDeleteRow) { _this.props.options.handleConfirmDeleteRow(function () { _this.deleteRow(dropRowKeys); }); } else if (confirm('Are you sure want delete?')) { _this.deleteRow(dropRowKeys); } } }; this.handleFilterData = function (filterObj) { _this.store.filter(filterObj); var result = undefined; if (_this.props.pagination) { var sizePerPage = _this.state.sizePerPage; result = _this.store.page(1, sizePerPage).get(); } else { result = _this.store.get(); } if (_this.props.options.afterColumnFilter) { _this.props.options.afterColumnFilter(filterObj, _this.store.getDataIgnoringPagination()); } _this.setState({ data: result, currPage: 1 }); }; this.handleExportCSV = function () { var result = _this.store.getDataIgnoringPagination(); var keys = []; _this.props.children.map(function (column) { if (column.props.hidden === false) { keys.push(column.props.dataField); } }); (0, _csv_export_util2['default'])(result, keys, _this.props.csvFileName); }; this.handleSearch = function (searchText) { _this.store.search(searchText); var result = undefined; if (_this.props.pagination) { var sizePerPage = _this.state.sizePerPage; result = _this.store.page(1, sizePerPage).get(); } else { result = _this.store.get(); } if (_this.props.options.afterSearch) { _this.props.options.afterSearch(searchText, _this.store.getDataIgnoringPagination()); } _this.setState({ data: result, currPage: 1 }); }; this._scrollHeader = function (e) { _this.refs.header.refs.container.scrollLeft = e.currentTarget.scrollLeft; }; this._adjustTable = function () { _this._adjustHeaderWidth(); _this._adjustHeight(); }; this._adjustHeaderWidth = function () { var header = _this.refs.header.refs.header; var headerContainer = _this.refs.header.refs.container; var tbody = _this.refs.body.refs.tbody; var firstRow = tbody.childNodes[0]; var isScroll = headerContainer.offsetWidth !== tbody.parentNode.offsetWidth; var scrollBarWidth = isScroll ? _util2['default'].getScrollBarWidth() : 0; if (firstRow && _this.store.getDataNum()) { var cells = firstRow.childNodes; for (var i = 0; i < cells.length; i++) { var cell = cells[i]; var computedStyle = getComputedStyle(cell); var width = parseFloat(computedStyle.width.replace('px', '')); if (_this.isIE) { var paddingLeftWidth = parseFloat(computedStyle.paddingLeft.replace('px', '')); var paddingRightWidth = parseFloat(computedStyle.paddingRight.replace('px', '')); var borderRightWidth = parseFloat(computedStyle.borderRightWidth.replace('px', '')); var borderLeftWidth = parseFloat(computedStyle.borderLeftWidth.replace('px', '')); width = width + paddingLeftWidth + paddingRightWidth + borderRightWidth + borderLeftWidth; } var lastPadding = cells.length - 1 === i ? scrollBarWidth : 0; if (width <= 0) { width = 120; cell.width = width + lastPadding + 'px'; } var result = width + lastPadding + 'px'; header.childNodes[i].style.width = result; header.childNodes[i].style.minWidth = result; } } }; this._adjustHeight = function () { if (_this.props.height.indexOf('%') === -1) { _this.refs.body.refs.container.style.height = parseFloat(_this.props.height, 10) - _this.refs.header.refs.container.offsetHeight + 'px'; } }; this.isIE = false; this._attachCellEditFunc(); if (_util2['default'].canUseDOM()) { this.isIE = document.documentMode; } if (!Array.isArray(this.props.data)) { this.store = new _storeTableDataStore.TableDataStore(this.props.data.getData()); this.props.data.clear(); this.props.data.on('change', function (data) { _this.store.setData(data); _this.setState({ data: _this.getTableData() }); }); } else { var copy = this.props.data.slice(); this.store = new _storeTableDataStore.TableDataStore(copy); } this.initTable(this.props); if (this.filter) { this.filter.on('onFilterChange', function (currentFilter) { _this.handleFilterData(currentFilter); }); } if (this.props.selectRow && this.props.selectRow.selected) { var copy = this.props.selectRow.selected.slice(); this.store.setSelectedRowKey(copy); } this.state = { data: this.getTableData(), currPage: this.props.options.page || 1, sizePerPage: this.props.options.sizePerPage || _Const2['default'].SIZE_PER_PAGE_LIST[0], selectedRowKeys: this.store.getSelectedRowKeys() }; } _createClass(BootstrapTable, [{ key: 'initTable', value: function initTable(props) { var _this2 = this; var keyField = props.keyField; var isKeyFieldDefined = typeof keyField === 'string' && keyField.length; _react2['default'].Children.forEach(props.children, function (column) { if (column.props.isKey) { if (keyField) { throw 'Error. Multiple key column be detected in TableHeaderColumn.'; } keyField = column.props.dataField; } if (column.props.filter) { // a column contains a filter if (!_this2.filter) { // first time create the filter on the BootstrapTable _this2.filter = new _Filter.Filter(); } // pass the filter to column with filter column.props.filter.emitter = _this2.filter; } }); var colInfos = this.getColumnsDescription(props).reduce(function (prev, curr) { prev[curr.name] = curr; return prev; }, {}); if (!isKeyFieldDefined && !keyField) { throw 'Error. No any key column defined in TableHeaderColumn.\n Use \'isKey={true}\' to specify a unique column after version 0.5.4.'; } this.store.setProps({ isPagination: props.pagination, keyField: keyField, colInfos: colInfos, multiColumnSearch: props.multiColumnSearch, remote: this.isRemoteDataSource() }); } }, { key: 'getTableData', value: function getTableData() { var _props = this.props; var options = _props.options; var pagination = _props.pagination; var result = []; if (options.sortName && options.sortOrder) { this.store.sort(options.sortOrder, options.sortName); } if (pagination) { var page = undefined; var sizePerPage = undefined; if (this.store.isChangedPage()) { sizePerPage = this.state.sizePerPage; page = this.state.currPage; } else { sizePerPage = options.sizePerPage || _Const2['default'].SIZE_PER_PAGE_LIST[0]; page = options.page || 1; } result = this.store.page(page, sizePerPage).get(); } else { result = this.store.get(); } return result; } }, { key: 'getColumnsDescription', value: function getColumnsDescription(_ref) { var children = _ref.children; return _react2['default'].Children.map(children, function (column, i) { return { name: column.props.dataField, align: column.props.dataAlign, sort: column.props.dataSort, format: column.props.dataFormat, formatExtraData: column.props.formatExtraData, filterFormatted: column.props.filterFormatted, editable: column.props.editable, hidden: column.props.hidden, searchable: column.props.searchable, className: column.props.columnClassName, width: column.props.width, text: column.props.children, sortFunc: column.props.sortFunc, index: i }; }); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { this.initTable(nextProps); var options = nextProps.options; var selectRow = nextProps.selectRow; if (Array.isArray(nextProps.data)) { this.store.setData(nextProps.data.slice()); var page = options.page || this.state.currPage; var sizePerPage = options.sizePerPage || this.state.sizePerPage; // #125 if (!options.page && page >= Math.ceil(nextProps.data.length / sizePerPage)) { page = 1; } var sortInfo = this.store.getSortInfo(); var sortField = options.sortName || (sortInfo ? sortInfo.sortField : undefined); var sortOrder = options.sortOrder || (sortInfo ? sortInfo.order : undefined); if (sortField && sortOrder) this.store.sort(sortOrder, sortField); var data = this.store.page(page, sizePerPage).get(); this.setState({ data: data, currPage: page, sizePerPage: sizePerPage }); } if (selectRow && selectRow.selected) { // set default select rows to store. var copy = selectRow.selected.slice(); this.store.setSelectedRowKey(copy); this.setState({ selectedRowKeys: copy }); } } }, { key: 'componentDidMount', value: function componentDidMount() { this._adjustTable(); window.addEventListener('resize', this._adjustTable); this.refs.body.refs.container.addEventListener('scroll', this._scrollHeader); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { window.removeEventListener('resize', this._adjustTable); this.refs.body.refs.container.removeEventListener('scroll', this._scrollHeader); if (this.filter) { this.filter.removeAllListeners('onFilterChange'); } } }, { key: 'componentDidUpdate', value: function componentDidUpdate() { this._adjustTable(); this._attachCellEditFunc(); if (this.props.options.afterTableComplete) { this.props.options.afterTableComplete(); } } }, { key: '_attachCellEditFunc', value: function _attachCellEditFunc() { var cellEdit = this.props.cellEdit; if (cellEdit) { this.props.cellEdit.__onCompleteEdit__ = this.handleEditCell.bind(this); if (cellEdit.mode !== _Const2['default'].CELL_EDIT_NONE) { this.props.selectRow.clickToSelect = false; } } } /** * Returns true if in the current configuration, * the datagrid should load its data remotely. * * @param {Object} [props] Optional. If not given, this.props will be used * @return {Boolean} */ }, { key: 'isRemoteDataSource', value: function isRemoteDataSource(props) { return (props || this.props).remote; } }, { key: 'render', value: function render() { var style = { height: this.props.height, maxHeight: this.props.maxHeight }; var columns = this.getColumnsDescription(this.props); var sortInfo = this.store.getSortInfo(); var pagination = this.renderPagination(); var toolBar = this.renderToolBar(); var tableFilter = this.renderTableFilter(columns); var isSelectAll = this.isSelectAll(); var sortIndicator = this.props.options.sortIndicator; if (typeof this.props.options.sortIndicator === 'undefined') sortIndicator = true; return _react2['default'].createElement( 'div', { className: 'react-bs-table-container' }, toolBar, _react2['default'].createElement( 'div', { className: 'react-bs-table', ref: 'table', style: style, onMouseEnter: this.handleMouseEnter, onMouseLeave: this.handleMouseLeave }, _react2['default'].createElement( _TableHeader2['default'], { ref: 'header', rowSelectType: this.props.selectRow.mode, hideSelectColumn: this.props.selectRow.hideSelectColumn, sortName: sortInfo ? sortInfo.sortField : undefined, sortOrder: sortInfo ? sortInfo.order : undefined, sortIndicator: sortIndicator, onSort: this.handleSort, onSelectAllRow: this.handleSelectAllRow, bordered: this.props.bordered, condensed: this.props.condensed, isFiltered: this.filter ? true : false, isSelectAll: isSelectAll }, this.props.children ), _react2['default'].createElement(_TableBody2['default'], { ref: 'body', style: style, data: this.state.data, columns: columns, trClassName: this.props.trClassName, striped: this.props.striped, bordered: this.props.bordered, hover: this.props.hover, keyField: this.store.getKeyField(), condensed: this.props.condensed, selectRow: this.props.selectRow, cellEdit: this.props.cellEdit, selectedRowKeys: this.state.selectedRowKeys, onRowClick: this.handleRowClick, onRowMouseOver: this.handleRowMouseOver, onRowMouseOut: this.handleRowMouseOut, onSelectRow: this.handleSelectRow, noDataText: this.props.options.noDataText }) ), tableFilter, pagination ); } }, { key: 'isSelectAll', value: function isSelectAll() { var defaultSelectRowKeys = this.store.getSelectedRowKeys(); var allRowKeys = this.store.getAllRowkey(); if (defaultSelectRowKeys.length !== allRowKeys.length) { return defaultSelectRowKeys.length === 0 ? false : 'indeterminate'; } else { return true; } } }, { key: 'cleanSelected', value: function cleanSelected() { this.store.setSelectedRowKey([]); this.setState({ selectedRowKeys: [] }); } }, { key: 'handleEditCell', value: function handleEditCell(newVal, rowIndex, colIndex) { var _props$cellEdit = this.props.cellEdit; var beforeSaveCell = _props$cellEdit.beforeSaveCell; var afterSaveCell = _props$cellEdit.afterSaveCell; var fieldName = undefined; _react2['default'].Children.forEach(this.props.children, function (column, i) { if (i === colIndex) { fieldName = column.props.dataField; return false; } }); if (beforeSaveCell) { var isValid = beforeSaveCell(this.state.data[rowIndex], fieldName, newVal); if (!isValid && typeof isValid !== 'undefined') { this.setState({ data: this.store.get() }); return; } } var result = this.store.edit(newVal, rowIndex, fieldName).get(); this.setState({ data: result }); if (afterSaveCell) { afterSaveCell(this.state.data[rowIndex], fieldName, newVal); } } }, { key: 'handleAddRowAtBegin', value: function handleAddRowAtBegin(newObj) { try { this.store.addAtBegin(newObj); } catch (e) { return e; } this._handleAfterAddingRow(newObj); } }, { key: 'getSizePerPage', value: function getSizePerPage() { return this.state.sizePerPage; } }, { key: 'getCurrentPage', value: function getCurrentPage() { return this.state.currPage; } }, { key: 'deleteRow', value: function deleteRow(dropRowKeys) { var result = undefined; this.store.remove(dropRowKeys); // remove selected Row this.store.setSelectedRowKey([]); // clear selected row key if (this.props.pagination) { var sizePerPage = this.state.sizePerPage; var currLastPage = Math.ceil(this.store.getDataNum() / sizePerPage); var currPage = this.state.currPage; if (currPage > currLastPage) currPage = currLastPage; result = this.store.page(currPage, sizePerPage).get(); this.setState({ data: result, selectedRowKeys: this.store.getSelectedRowKeys(), currPage: currPage }); } else { result = this.store.get(); this.setState({ data: result, selectedRowKeys: this.store.getSelectedRowKeys() }); } if (this.props.options.afterDeleteRow) { this.props.options.afterDeleteRow(dropRowKeys); } } }, { key: 'renderPagination', value: function renderPagination() { if (this.props.pagination) { var dataSize = undefined; if (this.isRemoteDataSource()) { dataSize = this.props.fetchInfo.dataTotalSize; } else { dataSize = this.store.getDataNum(); } var options = this.props.options; return _react2['default'].createElement( 'div', { className: 'react-bs-table-pagination' }, _react2['default'].createElement(_paginationPaginationList2['default'], { ref: 'pagination', currPage: this.state.currPage, changePage: this.handlePaginationData, sizePerPage: this.state.sizePerPage, sizePerPageList: options.sizePerPageList || _Const2['default'].SIZE_PER_PAGE_LIST, paginationSize: options.paginationSize || _Const2['default'].PAGINATION_SIZE, remote: this.isRemoteDataSource(), dataSize: dataSize, onSizePerPageList: options.onSizePerPageList, prePage: options.prePage || _Const2['default'].PRE_PAGE, nextPage: options.nextPage || _Const2['default'].NEXT_PAGE, firstPage: options.firstPage || _Const2['default'].FIRST_PAGE, lastPage: options.lastPage || _Const2['default'].LAST_PAGE }) ); } return null; } }, { key: 'renderToolBar', value: function renderToolBar() { var _props2 = this.props; var selectRow = _props2.selectRow; var insertRow = _props2.insertRow; var deleteRow = _props2.deleteRow; var search = _props2.search; var children = _props2.children; var enableShowOnlySelected = selectRow && selectRow.showOnlySelected; if (enableShowOnlySelected || insertRow || deleteRow || search || this.props.exportCSV) { var columns = undefined; if (Array.isArray(children)) { columns = children.map(function (column) { var props = column.props; return { name: props.children, field: props.dataField, // when you want same auto generate value and not allow edit, example ID field autoValue: props.autoValue || false, // for create editor, no params for column.editable() indicate that editor for new row editable: props.editable && typeof props.editable === 'function' ? props.editable() : props.editable, format: props.dataFormat ? function (value) { return props.dataFormat(value, null, props.formatExtraData).replace(/<.*?>/g, ''); } : false }; }); } else { columns = [{ name: children.props.children, field: children.props.dataField, editable: children.props.editable }]; } return _react2['default'].createElement( 'div', { className: 'react-bs-table-tool-bar' }, _react2['default'].createElement(_toolbarToolBar2['default'], { clearSearch: this.props.options.clearSearch, enableInsert: insertRow, enableDelete: deleteRow, enableSearch: search, enableExportCSV: this.props.exportCSV, enableShowOnlySelected: enableShowOnlySelected, columns: columns, searchPlaceholder: this.props.searchPlaceholder, onAddRow: this.handleAddRow, onDropRow: this.handleDropRow, onSearch: this.handleSearch, onExportCSV: this.handleExportCSV, onShowOnlySelected: this.handleShowOnlySelected }) ); } else { return null; } } }, { key: 'renderTableFilter', value: function renderTableFilter(columns) { if (this.props.columnFilter) { return _react2['default'].createElement(_TableFilter2['default'], { columns: columns, rowSelectType: this.props.selectRow.mode, onFilter: this.handleFilterData }); } else { return null; } } }, { key: '_handleAfterAddingRow', value: function _handleAfterAddingRow(newObj) { var result = undefined; if (this.props.pagination) { // if pagination is enabled and insert row be trigger, change to last page var sizePerPage = this.state.sizePerPage; var currLastPage = Math.ceil(this.store.getDataNum() / sizePerPage); result = this.store.page(currLastPage, sizePerPage).get(); this.setState({ data: result, currPage: currLastPage }); } else { result = this.store.get(); this.setState({ data: result }); } if (this.props.options.afterInsertRow) { this.props.options.afterInsertRow(newObj); } } }]); return BootstrapTable; })(_react.Component); BootstrapTable.propTypes = { keyField: _react.PropTypes.string, height: _react.PropTypes.string, maxHeight: _react.PropTypes.string, data: _react.PropTypes.oneOfType([_react.PropTypes.array, _react.PropTypes.object]), remote: _react.PropTypes.bool, // remote data, default is false striped: _react.PropTypes.bool, bordered: _react.PropTypes.bool, hover: _react.PropTypes.bool, condensed: _react.PropTypes.bool, pagination: _react.PropTypes.bool, searchPlaceholder: _react.PropTypes.string, selectRow: _react.PropTypes.shape({ mode: _react.PropTypes.oneOf([_Const2['default'].ROW_SELECT_NONE, _Const2['default'].ROW_SELECT_SINGLE, _Const2['default'].ROW_SELECT_MULTI]), bgColor: _react.PropTypes.string, selected: _react.PropTypes.array, onSelect: _react.PropTypes.func, onSelectAll: _react.PropTypes.func, clickToSelect: _react.PropTypes.bool, hideSelectColumn: _react.PropTypes.bool, clickToSelectAndEditCell: _react.PropTypes.bool, showOnlySelected: _react.PropTypes.bool }), cellEdit: _react.PropTypes.shape({ mode: _react.PropTypes.string, blurToSave: _react.PropTypes.bool, beforeSaveCell: _react.PropTypes.func, afterSaveCell: _react.PropTypes.func }), insertRow: _react.PropTypes.bool, deleteRow: _react.PropTypes.bool, search: _react.PropTypes.bool, columnFilter: _react.PropTypes.bool, trClassName: _react.PropTypes.any, options: _react.PropTypes.shape({ clearSearch: _react.PropTypes.bool, sortName: _react.PropTypes.string, sortOrder: _react.PropTypes.string, sortIndicator: _react.PropTypes.bool, afterTableComplete: _react.PropTypes.func, afterDeleteRow: _react.PropTypes.func, afterInsertRow: _react.PropTypes.func, afterSearch: _react.PropTypes.func, afterColumnFilter: _react.PropTypes.func, onRowClick: _react.PropTypes.func, page: _react.PropTypes.number, sizePerPageList: _react.PropTypes.array, sizePerPage: _react.PropTypes.number, paginationSize: _react.PropTypes.number, onSortChange: _react.PropTypes.func, onPageChange: _react.PropTypes.func, onSizePerPageList: _react.PropTypes.func, noDataText: _react.PropTypes.string, handleConfirmDeleteRow: _react.PropTypes.func, prePage: _react.PropTypes.string, nextPage: _react.PropTypes.string, firstPage: _react.PropTypes.string, lastPage: _react.PropTypes.string }), fetchInfo: _react.PropTypes.shape({ dataTotalSize: _react.PropTypes.number }), exportCSV: _react.PropTypes.bool, csvFileName: _react.PropTypes.string }; BootstrapTable.defaultProps = { height: '100%', maxHeight: undefined, striped: false, bordered: true, hover: false, condensed: false, pagination: false, searchPlaceholder: undefined, selectRow: { mode: _Const2['default'].ROW_SELECT_NONE, bgColor: _Const2['default'].ROW_SELECT_BG_COLOR, selected: [], onSelect: undefined, onSelectAll: undefined, clickToSelect: false, hideSelectColumn: false, clickToSelectAndEditCell: false, showOnlySelected: false }, cellEdit: { mode: _Const2['default'].CELL_EDIT_NONE, blurToSave: false, beforeSaveCell: undefined, afterSaveCell: undefined }, insertRow: false, deleteRow: false, search: false, multiColumnSearch: false, columnFilter: false, trClassName: '', options: { clearSearch: false, sortName: undefined, sortOrder: undefined, sortIndicator: true, afterTableComplete: undefined, afterDeleteRow: undefined, afterInsertRow: undefined, afterSearch: undefined, afterColumnFilter: undefined, onRowClick: undefined, onMouseLeave: undefined, onMouseEnter: undefined, onRowMouseOut: undefined, onRowMouseOver: undefined, page: undefined, sizePerPageList: _Const2['default'].SIZE_PER_PAGE_LIST, sizePerPage: undefined, paginationSize: _Const2['default'].PAGINATION_SIZE, onSizePerPageList: undefined, noDataText: undefined, handleConfirmDeleteRow: undefined, prePage: _Const2['default'].PRE_PAGE, nextPage: _Const2['default'].NEXT_PAGE, firstPage: _Const2['default'].FIRST_PAGE, lastPage: _Const2['default'].LAST_PAGE }, fetchInfo: { dataTotalSize: 0 }, exportCSV: false, csvFileName: undefined }; exports['default'] = BootstrapTable; module.exports = exports['default']; /***/ }, /* 2 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_2__; /***/ }, /* 3 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = { SORT_DESC: 'desc', SORT_ASC: 'asc', SIZE_PER_PAGE: 10, NEXT_PAGE: '>', LAST_PAGE: '>>', PRE_PAGE: '<', FIRST_PAGE: '<<', ROW_SELECT_BG_COLOR: '', ROW_SELECT_NONE: 'none', ROW_SELECT_SINGLE: 'radio', ROW_SELECT_MULTI: 'checkbox', CELL_EDIT_NONE: 'none', CELL_EDIT_CLICK: 'click', CELL_EDIT_DBCLICK: 'dbclick', SIZE_PER_PAGE_LIST: [10, 25, 30, 50], PAGINATION_SIZE: 5, NO_DATA_TEXT: 'There is no data to display', SHOW_ONLY_SELECT: 'Show Selected Only', SHOW_ALL: 'Show All', FILTER_DELAY: 500, FILTER_TYPE: { TEXT: 'TextFilter', REGEX: 'RegexFilter', SELECT: 'SelectFilter', NUMBER: 'NumberFilter', DATE: 'DateFilter', CUSTOM: 'CustomFilter' } }; module.exports = exports['default']; /***/ }, /* 4 */ /***/ 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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(5); var _reactDom2 = _interopRequireDefault(_reactDom); var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var _classnames = __webpack_require__(6); var _classnames2 = _interopRequireDefault(_classnames); var _SelectRowHeaderColumn = __webpack_require__(7); var _SelectRowHeaderColumn2 = _interopRequireDefault(_SelectRowHeaderColumn); var Checkbox = (function (_Component) { _inherits(Checkbox, _Component); function Checkbox() { _classCallCheck(this, Checkbox); _get(Object.getPrototypeOf(Checkbox.prototype), 'constructor', this).apply(this, arguments); } _createClass(Checkbox, [{ key: 'componentDidMount', value: function componentDidMount() { this.update(this.props.checked); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { this.update(props.checked); } }, { key: 'update', value: function update(checked) { _reactDom2['default'].findDOMNode(this).indeterminate = checked === 'indeterminate'; } }, { key: 'render', value: function render() { return _react2['default'].createElement('input', { className: 'react-bs-select-all', type: 'checkbox', checked: this.props.checked, onChange: this.props.onChange }); } }]); return Checkbox; })(_react.Component); var TableHeader = (function (_Component2) { _inherits(TableHeader, _Component2); function TableHeader() { _classCallCheck(this, TableHeader); _get(Object.getPrototypeOf(TableHeader.prototype), 'constructor', this).apply(this, arguments); } _createClass(TableHeader, [{ key: 'render', value: function render() { var containerClasses = (0, _classnames2['default'])('react-bs-container-header', 'table-header-wrapper'); var tableClasses = (0, _classnames2['default'])('table', 'table-hover', { 'table-bordered': this.props.bordered, 'table-condensed': this.props.condensed }); var selectRowHeaderCol = null; if (!this.props.hideSelectColumn) selectRowHeaderCol = this.renderSelectRowHeader(); this._attachClearSortCaretFunc(); return _react2['default'].createElement( 'div', { ref: 'container', className: containerClasses }, _react2['default'].createElement( 'table', { className: tableClasses }, _react2['default'].createElement( 'thead', null, _react2['default'].createElement( 'tr', { ref: 'header' }, selectRowHeaderCol, this.props.children ) ) ) ); } }, { key: 'renderSelectRowHeader', value: function renderSelectRowHeader() { if (this.props.rowSelectType === _Const2['default'].ROW_SELECT_SINGLE) { return _react2['default'].createElement(_SelectRowHeaderColumn2['default'], null); } else if (this.props.rowSelectType === _Const2['default'].ROW_SELECT_MULTI) { return _react2['default'].createElement( _SelectRowHeaderColumn2['default'], null, _react2['default'].createElement(Checkbox, { onChange: this.props.onSelectAllRow, checked: this.props.isSelectAll }) ); } else { return null; } } }, { key: '_attachClearSortCaretFunc', value: function _attachClearSortCaretFunc() { var _props = this.props; var sortIndicator = _props.sortIndicator; var children = _props.children; var sortName = _props.sortName; var sortOrder = _props.sortOrder; var onSort = _props.onSort; if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { var field = children[i].props.dataField; var sort = field === sortName ? sortOrder : undefined; this.props.children[i] = _react2['default'].cloneElement(children[i], { key: i, onSort: onSort, sort: sort, sortIndicator: sortIndicator }); } } else { var field = children.props.dataField; var sort = field === sortName ? sortOrder : undefined; this.props.children = _react2['default'].cloneElement(children, { key: 0, onSort: onSort, sort: sort, sortIndicator: sortIndicator }); } } }]); return TableHeader; })(_react.Component); TableHeader.propTypes = { rowSelectType: _react.PropTypes.string, onSort: _react.PropTypes.func, onSelectAllRow: _react.PropTypes.func, sortName: _react.PropTypes.string, sortOrder: _react.PropTypes.string, hideSelectColumn: _react.PropTypes.bool, bordered: _react.PropTypes.bool, condensed: _react.PropTypes.bool, isFiltered: _react.PropTypes.bool, isSelectAll: _react.PropTypes.oneOf([true, 'indeterminate', false]), sortIndicator: _react.PropTypes.bool }; exports['default'] = TableHeader; module.exports = exports['default']; /***/ }, /* 5 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_5__; /***/ }, /* 6 */ /***/ 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; } }()); /***/ }, /* 7 */ /***/ 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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var SelectRowHeaderColumn = (function (_Component) { _inherits(SelectRowHeaderColumn, _Component); function SelectRowHeaderColumn() { _classCallCheck(this, SelectRowHeaderColumn); _get(Object.getPrototypeOf(SelectRowHeaderColumn.prototype), 'constructor', this).apply(this, arguments); } _createClass(SelectRowHeaderColumn, [{ key: 'render', value: function render() { return _react2['default'].createElement( 'th', { style: { textAlign: 'center' } }, this.props.children ); } }]); return SelectRowHeaderColumn; })(_react.Component); SelectRowHeaderColumn.propTypes = { children: _react.PropTypes.node }; exports['default'] = SelectRowHeaderColumn; module.exports = exports['default']; /***/ }, /* 8 */ /***/ 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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var _TableRow = __webpack_require__(9); var _TableRow2 = _interopRequireDefault(_TableRow); var _TableColumn = __webpack_require__(10); var _TableColumn2 = _interopRequireDefault(_TableColumn); var _TableEditColumn = __webpack_require__(11); var _TableEditColumn2 = _interopRequireDefault(_TableEditColumn); var _classnames = __webpack_require__(6); var _classnames2 = _interopRequireDefault(_classnames); var isFun = function isFun(obj) { return obj && typeof obj === 'function'; }; var TableBody = (function (_Component) { _inherits(TableBody, _Component); function TableBody(props) { var _this = this; _classCallCheck(this, TableBody); _get(Object.getPrototypeOf(TableBody.prototype), 'constructor', this).call(this, props); this.handleRowMouseOut = function (rowIndex, event) { var targetRow = _this.props.data[rowIndex]; _this.props.onRowMouseOut(targetRow, event); }; this.handleRowMouseOver = function (rowIndex, event) { var targetRow = _this.props.data[rowIndex]; _this.props.onRowMouseOver(targetRow, event); }; this.handleRowClick = function (rowIndex) { var selectedRow = undefined; var _props = _this.props; var data = _props.data; var onRowClick = _props.onRowClick; data.forEach(function (row, i) { if (i === rowIndex - 1) { selectedRow = row; } }); onRowClick(selectedRow); }; this.handleSelectRow = function (rowIndex, isSelected) { var selectedRow = undefined; var _props2 = _this.props; var data = _props2.data; var onSelectRow = _props2.onSelectRow; data.forEach(function (row, i) { if (i === rowIndex - 1) { selectedRow = row; return false; } }); onSelectRow(selectedRow, isSelected); }; this.handleSelectRowColumChange = function (e) { if (!_this.props.selectRow.clickToSelect || !_this.props.selectRow.clickToSelectAndEditCell) { _this.handleSelectRow(e.currentTarget.parentElement.parentElement.rowIndex + 1, e.currentTarget.checked); } }; this.handleEditCell = function (rowIndex, columnIndex) { _this.editing = true; if (_this._isSelectRowDefined()) { columnIndex--; if (_this.props.selectRow.hideSelectColumn) columnIndex++; } rowIndex--; var stateObj = { currEditCell: { rid: rowIndex, cid: columnIndex } }; if (_this.props.selectRow.clickToSelectAndEditCell) { _this.handleSelectRow(rowIndex + 1, true); } _this.setState(stateObj); }; this.handleCompleteEditCell = function (newVal, rowIndex, columnIndex) { _this.setState({ currEditCell: null }); if (newVal !== null) { _this.props.cellEdit.__onCompleteEdit__(newVal, rowIndex, columnIndex); } }; this.state = { currEditCell: null }; this.editing = false; } _createClass(TableBody, [{ key: 'render', value: function render() { var tableClasses = (0, _classnames2['default'])('table', { 'table-striped': this.props.striped, 'table-bordered': this.props.bordered, 'table-hover': this.props.hover, 'table-condensed': this.props.condensed }); var isSelectRowDefined = this._isSelectRowDefined(); var tableHeader = this.renderTableHeader(isSelectRowDefined); var tableRows = this.props.data.map(function (data, r) { var tableColumns = this.props.columns.map(function (column, i) { var fieldValue = data[column.name]; if (this.editing && column.name !== this.props.keyField && // Key field can't be edit column.editable && // column is editable? default is true, user can set it false this.state.currEditCell !== null && this.state.currEditCell.rid === r && this.state.currEditCell.cid === i) { var editable = column.editable; var format = column.format ? function (value) { return column.format(value, data, column.formatExtraData).replace(/<.*?>/g, ''); } : false; if (isFun(column.editable)) { editable = column.editable(fieldValue, data, r, i); } return _react2['default'].createElement( _TableEditColumn2['default'], { completeEdit: this.handleCompleteEditCell, // add by bluespring for column editor customize editable: editable, format: column.format ? format : false, key: i, blurToSave: this.props.cellEdit.blurToSave, rowIndex: r, colIndex: i }, fieldValue ); } else { // add by bluespring for className customize var columnChild = fieldValue; var tdClassName = column.className; if (isFun(column.className)) { tdClassName = column.className(fieldValue, data, r, i); } if (typeof column.format !== 'undefined') { var formattedValue = column.format(fieldValue, data, column.formatExtraData); if (!_react2['default'].isValidElement(formattedValue)) { columnChild = _react2['default'].createElement('div', { dangerouslySetInnerHTML: { __html: formattedValue } }); } else { columnChild = formattedValue; } } return _react2['default'].createElement( _TableColumn2['default'], { key: i, dataAlign: column.align, className: tdClassName, cellEdit: this.props.cellEdit, hidden: column.hidden, onEdit: this.handleEditCell, width: column.width }, columnChild ); } }, this); var selected = this.props.selectedRowKeys.indexOf(data[this.props.keyField]) !== -1; var selectRowColumn = isSelectRowDefined && !this.props.selectRow.hideSelectColumn ? this.renderSelectRowColumn(selected) : null; // add by bluespring for className customize var trClassName = this.props.trClassName; if (isFun(this.props.trClassName)) { trClassName = this.props.trClassName(data, r); } return _react2['default'].createElement( _TableRow2['default'], { isSelected: selected, key: r, className: trClassName, selectRow: isSelectRowDefined ? this.props.selectRow : undefined, enableCellEdit: this.props.cellEdit.mode !== _Const2['default'].CELL_EDIT_NONE, onRowClick: this.handleRowClick, onRowMouseOver: this.handleRowMouseOver, onRowMouseOut: this.handleRowMouseOut, onSelectRow: this.handleSelectRow }, selectRowColumn, tableColumns ); }, this); if (tableRows.length === 0) { tableRows.push(_react2['default'].createElement( _TableRow2['default'], { key: '##table-empty##' }, _react2['default'].createElement( 'td', { colSpan: this.props.columns.length + (isSelectRowDefined ? 1 : 0), className: 'react-bs-table-no-data' }, this.props.noDataText || _Const2['default'].NO_DATA_TEXT ) )); } this.editing = false; return _react2['default'].createElement( 'div', { ref: 'container', className: 'react-bs-container-body', style: this.props.style }, _react2['default'].createElement( 'table', { className: tableClasses }, tableHeader, _react2['default'].createElement( 'tbody', { ref: 'tbody' }, tableRows ) ) ); } }, { key: 'renderTableHeader', value: function renderTableHeader(isSelectRowDefined) { var selectRowHeader = null; if (isSelectRowDefined) { var style = { width: 30, minWidth: 30 }; if (!this.props.selectRow.hideSelectColumn) { selectRowHeader = _react2['default'].createElement('col', { style: style, key: -1 }); } } var theader = this.props.columns.map(function (column, i) { var width = column.width === null ? column.width : parseInt(column.width, 10); var style = { display: column.hidden ? 'none' : null, width: width, minWidth: width /** add min-wdth to fix user assign column width not eq offsetWidth in large column table **/ }; return _react2['default'].createElement('col', { style: style, key: i, className: column.className }); }); return _react2['default'].createElement( 'colgroup', { ref: 'header' }, selectRowHeader, theader ); } }, { key: 'renderSelectRowColumn', value: function renderSelectRowColumn(selected) { if (this.props.selectRow.mode === _Const2['default'].ROW_SELECT_SINGLE) { return _react2['default'].createElement( _TableColumn2['default'], { dataAlign: 'center' }, _react2['default'].createElement('input', { type: 'radio', checked: selected, onChange: this.handleSelectRowColumChange }) ); } else { return _react2['default'].createElement( _TableColumn2['default'], { dataAlign: 'center' }, _react2['default'].createElement('input', { type: 'checkbox', checked: selected, onChange: this.handleSelectRowColumChange }) ); } } }, { key: '_isSelectRowDefined', value: function _isSelectRowDefined() { return this.props.selectRow.mode === _Const2['default'].ROW_SELECT_SINGLE || this.props.selectRow.mode === _Const2['default'].ROW_SELECT_MULTI; } }]); return TableBody; })(_react.Component); TableBody.propTypes = { data: _react.PropTypes.array, columns: _react.PropTypes.array, striped: _react.PropTypes.bool, bordered: _react.PropTypes.bool, hover: _react.PropTypes.bool, condensed: _react.PropTypes.bool, keyField: _react.PropTypes.string, selectedRowKeys: _react.PropTypes.array, onRowClick: _react.PropTypes.func, onSelectRow: _react.PropTypes.func, noDataText: _react.PropTypes.string, style: _react.PropTypes.object }; exports['default'] = TableBody; module.exports = exports['default']; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var TableRow = (function (_Component) { _inherits(TableRow, _Component); function TableRow(props) { var _this = this; _classCallCheck(this, TableRow); _get(Object.getPrototypeOf(TableRow.prototype), 'constructor', this).call(this, props); this.rowClick = function (e) { if (e.target.tagName !== 'INPUT' && e.target.tagName !== 'SELECT' && e.target.tagName !== 'TEXTAREA') { (function () { var rowIndex = e.currentTarget.rowIndex + 1; if (_this.props.selectRow) { if (_this.props.selectRow.clickToSelect) { _this.props.onSelectRow(rowIndex, !_this.props.isSelected); } else if (_this.props.selectRow.clickToSelectAndEditCell) { _this.clickNum++; /** if clickToSelectAndEditCell is enabled, * there should be a delay to prevent a selection changed when * user dblick to edit cell on same row but different cell **/ setTimeout(function () { if (_this.clickNum === 1) { _this.props.onSelectRow(rowIndex, !_this.props.isSelected); } _this.clickNum = 0; }, 200); } } if (_this.props.onRowClick) _this.props.onRowClick(rowIndex); })(); } }; this.rowMouseOut = function (e) { if (_this.props.onRowMouseOut) { _this.props.onRowMouseOut(e.currentTarget.rowIndex, e); } }; this.rowMouseOver = function (e) { if (_this.props.onRowMouseOver) { _this.props.onRowMouseOver(e.currentTarget.rowIndex, e); } }; this.clickNum = 0; } _createClass(TableRow, [{ key: 'render', value: function render() { this.clickNum = 0; var trCss = { style: { backgroundColor: this.props.isSelected ? this.props.selectRow.bgColor : null }, className: (this.props.isSelected && this.props.selectRow.className ? this.props.selectRow.className : '') + (this.props.className || '') }; if (this.props.selectRow && (this.props.selectRow.clickToSelect || this.props.selectRow.clickToSelectAndEditCell) || this.props.onRowClick) { return _react2['default'].createElement( 'tr', _extends({}, trCss, { onMouseOver: this.rowMouseOver, onMouseOut: this.rowMouseOut, onClick: this.rowClick }), this.props.children ); } else { return _react2['default'].createElement( 'tr', trCss, this.props.children ); } } }]); return TableRow; })(_react.Component); TableRow.propTypes = { isSelected: _react.PropTypes.bool, enableCellEdit: _react.PropTypes.bool, onRowClick: _react.PropTypes.func, onSelectRow: _react.PropTypes.func, onRowMouseOut: _react.PropTypes.func, onRowMouseOver: _react.PropTypes.func }; TableRow.defaultProps = { onRowClick: undefined }; exports['default'] = TableRow; module.exports = exports['default']; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var TableColumn = (function (_Component) { _inherits(TableColumn, _Component); function TableColumn(props) { var _this = this; _classCallCheck(this, TableColumn); _get(Object.getPrototypeOf(TableColumn.prototype), 'constructor', this).call(this, props); this.handleCellEdit = function (e) { if (_this.props.cellEdit.mode === _Const2['default'].CELL_EDIT_DBCLICK) { if (document.selection && document.selection.empty) { document.selection.empty(); } else if (window.getSelection) { var sel = window.getSelection(); sel.removeAllRanges(); } } _this.props.onEdit(e.currentTarget.parentElement.rowIndex + 1, e.currentTarget.cellIndex); }; } /* eslint no-unused-vars: [0, { "args": "after-used" }] */ _createClass(TableColumn, [{ key: 'shouldComponentUpdate', value: function shouldComponentUpdate(nextProps, nextState) { var children = this.props.children; var shouldUpdated = this.props.width !== nextProps.width || this.props.className !== nextProps.className || this.props.hidden !== nextProps.hidden || this.props.dataAlign !== nextProps.dataAlign || typeof children !== typeof nextProps.children || ('' + this.props.onEdit).toString() !== ('' + nextProps.onEdit).toString(); if (shouldUpdated) { return shouldUpdated; } if (typeof children === 'object' && children !== null && children.props !== null) { if (children.props.type === 'checkbox' || children.props.type === 'radio') { shouldUpdated = shouldUpdated || children.props.type !== nextProps.children.props.type || children.props.checked !== nextProps.children.props.checked; } else { shouldUpdated = true; } } else { shouldUpdated = shouldUpdated || children !== nextProps.children; } if (shouldUpdated) { return shouldUpdated; } if (!(this.props.cellEdit && nextProps.cellEdit)) { return false; } else { return shouldUpdated || this.props.cellEdit.mode !== nextProps.cellEdit.mode; } } }, { key: 'render', value: function render() { var tdStyle = { textAlign: this.props.dataAlign, display: this.props.hidden ? 'none' : null }; var opts = {}; if (this.props.cellEdit) { if (this.props.cellEdit.mode === _Const2['default'].CELL_EDIT_CLICK) { opts.onClick = this.handleCellEdit; } else if (this.props.cellEdit.mode === _Const2['default'].CELL_EDIT_DBCLICK) { opts.onDoubleClick = this.handleCellEdit; } } return _react2['default'].createElement( 'td', _extends({ style: tdStyle, className: this.props.className }, opts), this.props.children ); } }]); return TableColumn; })(_react.Component); TableColumn.propTypes = { dataAlign: _react.PropTypes.string, hidden: _react.PropTypes.bool, className: _react.PropTypes.string, children: _react.PropTypes.node }; TableColumn.defaultProps = { dataAlign: 'left', hidden: false, className: '' }; exports['default'] = TableColumn; module.exports = exports['default']; /***/ }, /* 11 */ /***/ 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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Editor = __webpack_require__(12); var _Editor2 = _interopRequireDefault(_Editor); var _NotificationJs = __webpack_require__(13); var _NotificationJs2 = _interopRequireDefault(_NotificationJs); var _classnames = __webpack_require__(6); var _classnames2 = _interopRequireDefault(_classnames); var TableEditColumn = (function (_Component) { _inherits(TableEditColumn, _Component); function TableEditColumn(props) { var _this = this; _classCallCheck(this, TableEditColumn); _get(Object.getPrototypeOf(TableEditColumn.prototype), 'constructor', this).call(this, props); this.handleKeyPress = function (e) { if (e.keyCode === 13) { // Pressed ENTER var value = e.currentTarget.type === 'checkbox' ? _this._getCheckBoxValue(e) : e.currentTarget.value; if (!_this.validator(value)) { return; } _this.props.completeEdit(value, _this.props.rowIndex, _this.props.colIndex); } else if (e.keyCode === 27) { _this.props.completeEdit(null, _this.props.rowIndex, _this.props.colIndex); } }; this.handleBlur = function (e) { if (_this.props.blurToSave) { var value = e.currentTarget.type === 'checkbox' ? _this._getCheckBoxValue(e) : e.currentTarget.value; if (!_this.validator(value)) { return; } _this.props.completeEdit(value, _this.props.rowIndex, _this.props.colIndex); } }; this.timeouteClear = 0; this.state = { shakeEditor: false }; } _createClass(TableEditColumn, [{ key: 'validator', value: function validator(value) { var ts = this; if (ts.props.editable.validator) { var valid = ts.props.editable.validator(value); if (!valid) { ts.refs.notifier.notice('error', valid, 'Pressed ESC can cancel'); var input = ts.refs.inputRef; // animate input ts.clearTimeout(); ts.setState({ shakeEditor: true }); ts.timeouteClear = setTimeout(function () { ts.setState({ shakeEditor: false }); }, 300); input.focus(); return false; } } return true; } }, { key: 'clearTimeout', value: (function (_clearTimeout) { function clearTimeout() { return _clearTimeout.apply(this, arguments); } clearTimeout.toString = function () { return _clearTimeout.toString(); }; return clearTimeout; })(function () { if (this.timeouteClear !== 0) { clearTimeout(this.timeouteClear); this.timeouteClear = 0; } }) }, { key: 'componentDidMount', value: function componentDidMount() { this.refs.inputRef.focus(); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.clearTimeout(); } }, { key: 'render', value: function render() { var _props = this.props; var editable = _props.editable; var format = _props.format; var children = _props.children; var shakeEditor = this.state.shakeEditor; var attr = { ref: 'inputRef', onKeyDown: this.handleKeyPress, onBlur: this.handleBlur }; // put placeholder if exist editable.placeholder && (attr.placeholder = editable.placeholder); var editorClass = (0, _classnames2['default'])({ 'animated': shakeEditor, 'shake': shakeEditor }); return _react2['default'].createElement( 'td', { ref: 'td', style: { position: 'relative' } }, (0, _Editor2['default'])(editable, attr, format, editorClass, children || ''), _react2['default'].createElement(_NotificationJs2['default'], { ref: 'notifier' }) ); } }, { key: '_getCheckBoxValue', value: function _getCheckBoxValue(e) { var value = ''; var values = e.currentTarget.value.split(':'); value = e.currentTarget.checked ? values[0] : values[1]; return value; } }]); return TableEditColumn; })(_react.Component); TableEditColumn.propTypes = { completeEdit: _react.PropTypes.func, rowIndex: _react.PropTypes.number, colIndex: _react.PropTypes.number, blurToSave: _react.PropTypes.bool, editable: _react.PropTypes.oneOfType([_react.PropTypes.bool, _react.PropTypes.object]), format: _react.PropTypes.oneOfType([_react.PropTypes.bool, _react.PropTypes.func]), children: _react.PropTypes.node }; exports['default'] = TableEditColumn; module.exports = exports['default']; /***/ }, /* 12 */ /***/ 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; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var editor = function editor(editable, attr, format, editorClass, defaultValue) { if (editable === true || typeof editable === 'string') { // simple declare var type = editable ? 'text' : editable; return _react2['default'].createElement('input', _extends({}, attr, { type: type, defaultValue: defaultValue, className: (editorClass || '') + ' form-control editor edit-text' })); } else if (!editable) { var type = editable ? 'text' : editable; return _react2['default'].createElement('input', _extends({}, attr, { type: type, defaultValue: defaultValue, disabled: 'disabled', className: (editorClass || '') + ' form-control editor edit-text' })); } else if (editable.type) { // standard declare // put style if exist editable.style && (attr.style = editable.style); // put class if exist attr.className = (editorClass || '') + ' form-control editor edit-' + editable.type + (editable.className ? ' ' + editable.className : ''); if (editable.type === 'select') { // process select input var options = []; var values = editable.options.values; if (Array.isArray(values)) { (function () { // only can use arrray data for options var rowValue = undefined; options = values.map(function (d, i) { rowValue = format ? format(d) : d; return _react2['default'].createElement( 'option', { key: 'option' + i, value: d }, rowValue ); }); })(); } return _react2['default'].createElement( 'select', _extends({}, attr, { defaultValue: defaultValue }), options ); } else if (editable.type === 'textarea') { var _ret2 = (function () { // process textarea input // put other if exist editable.cols && (attr.cols = editable.cols); editable.rows && (attr.rows = editable.rows); var saveBtn = undefined; var keyUpHandler = attr.onKeyDown; if (keyUpHandler) { attr.onKeyDown = function (e) { if (e.keyCode !== 13) { // not Pressed ENTER keyUpHandler(e); } }; saveBtn = _react2['default'].createElement( 'button', { className: 'btn btn-info btn-xs textarea-save-btn', onClick: keyUpHandler }, 'save' ); } return { v: _react2['default'].createElement( 'div', null, _react2['default'].createElement('textarea', _extends({}, attr, { defaultValue: defaultValue })), saveBtn ) }; })(); if (typeof _ret2 === 'object') return _ret2.v; } else if (editable.type === 'checkbox') { var values = 'true:false'; if (editable.options && editable.options.values) { // values = editable.options.values.split(':'); values = editable.options.values; } attr.className = attr.className.replace('form-control', ''); attr.className += ' checkbox pull-right'; var checked = defaultValue && defaultValue.toString() === values.split(':')[0] ? true : false; return _react2['default'].createElement('input', _extends({}, attr, { type: 'checkbox', value: values, defaultChecked: checked })); } else { // process other input type. as password,url,email... return _react2['default'].createElement('input', _extends({}, attr, { type: 'text', defaultValue: defaultValue })); } } // default return for other case of editable return _react2['default'].createElement('input', _extends({}, attr, { type: 'text', className: (editorClass || '') + ' form-control editor edit-text' })); }; exports['default'] = editor; module.exports = exports['default']; /***/ }, /* 13 */ /***/ 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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _reactToastr = __webpack_require__(14); var ToastrMessageFactory = _react2['default'].createFactory(_reactToastr.ToastMessage.animation); var Notification = (function (_Component) { _inherits(Notification, _Component); function Notification() { _classCallCheck(this, Notification); _get(Object.getPrototypeOf(Notification.prototype), 'constructor', this).apply(this, arguments); } _createClass(Notification, [{ key: 'notice', // allow type is success,info,warning,error value: function notice(type, msg, title) { this.refs.toastr[type](msg, title, { mode: 'single', timeOut: 5000, extendedTimeOut: 1000, showAnimation: 'animated bounceIn', hideAnimation: 'animated bounceOut' }); } }, { key: 'render', value: function render() { return _react2['default'].createElement(_reactToastr.ToastContainer, { ref: 'toastr', toastMessageFactory: ToastrMessageFactory, id: 'toast-container', className: 'toast-top-right' }); } }]); return Notification; })(_react.Component); exports['default'] = Notification; module.exports = exports['default']; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ToastMessage = exports.ToastContainer = undefined; var _ToastContainer = __webpack_require__(15); var _ToastContainer2 = _interopRequireDefault(_ToastContainer); var _ToastMessage = __webpack_require__(22); var _ToastMessage2 = _interopRequireDefault(_ToastMessage); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.ToastContainer = _ToastContainer2.default; exports.ToastMessage = _ToastMessage2.default; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 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; }; }(); Object.defineProperty(exports, "__esModule", { value: true }); var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _reactAddonsUpdate = __webpack_require__(16); var _reactAddonsUpdate2 = _interopRequireDefault(_reactAddonsUpdate); var _ToastMessage = __webpack_require__(22); var _ToastMessage2 = _interopRequireDefault(_ToastMessage); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var ToastContainer = function (_Component) { _inherits(ToastContainer, _Component); function ToastContainer() { var _Object$getPrototypeO; var _temp, _this, _ret; _classCallCheck(this, ToastContainer); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_Object$getPrototypeO = Object.getPrototypeOf(ToastContainer)).call.apply(_Object$getPrototypeO, [this].concat(args))), _this), _this.state = { toasts: [], toastId: 0, previousMessage: null }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(ToastContainer, [{ key: "error", value: function error(message, title, optionsOverride) { this._notify(this.props.toastType.error, message, title, optionsOverride); } }, { key: "info", value: function info(message, title, optionsOverride) { this._notify(this.props.toastType.info, message, title, optionsOverride); } }, { key: "success", value: function success(message, title, optionsOverride) { this._notify(this.props.toastType.success, message, title, optionsOverride); } }, { key: "warning", value: function warning(message, title, optionsOverride) { this._notify(this.props.toastType.warning, message, title, optionsOverride); } }, { key: "clear", value: function clear() { var _this2 = this; Object.keys(this.refs).forEach(function (key) { _this2.refs[key].hideToast(false); }); } }, { key: "render", value: function render() { var _this3 = this; return _react2.default.createElement( "div", _extends({}, this.props, { "aria-live": "polite", role: "alert" }), this.state.toasts.map(function (toast) { return _this3.props.toastMessageFactory(toast); }) ); } }, { key: "_notify", value: function _notify(type, message, title) { var _this4 = this; var optionsOverride = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3]; if (this.props.preventDuplicates) { if (this.state.previousMessage === message) { return; } } var key = this.state.toastId++; var toastId = key; var newToast = (0, _reactAddonsUpdate2.default)(optionsOverride, { $merge: { type: type, title: title, message: message, toastId: toastId, key: key, ref: "toasts__" + key, handleOnClick: function handleOnClick(e) { if ("function" === typeof optionsOverride.handleOnClick) { optionsOverride.handleOnClick(); } return _this4._handle_toast_on_click(e); }, handleRemove: this._handle_toast_remove.bind(this) } }); var toastOperation = _defineProperty({}, "" + (this.props.newestOnTop ? "$unshift" : "$push"), [newToast]); var nextState = (0, _reactAddonsUpdate2.default)(this.state, { toasts: toastOperation, previousMessage: { $set: message } }); this.setState(nextState); } }, { key: "_handle_toast_on_click", value: function _handle_toast_on_click(event) { this.props.onClick(event); if (event.defaultPrevented) { return; } event.preventDefault(); event.stopPropagation(); } }, { key: "_handle_toast_remove", value: function _handle_toast_remove(toastId) { var _this5 = this; var operationName = "" + (this.props.newestOnTop ? "reduceRight" : "reduce"); this.state.toasts[operationName](function (found, toast, index) { if (found || toast.toastId !== toastId) { return false; } _this5.setState((0, _reactAddonsUpdate2.default)(_this5.state, { toasts: { $splice: [[index, 1]] } })); return true; }, false); } }]); return ToastContainer; }(_react.Component); ToastContainer.defaultProps = { toastType: { error: "error", info: "info", success: "success", warning: "warning" }, id: "toast-container", toastMessageFactory: _react2.default.createFactory(_ToastMessage2.default), preventDuplicates: false, newestOnTop: true, onClick: function onClick() {} }; exports.default = ToastContainer; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(17); /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule update */ /* global hasOwnProperty:true */ 'use strict'; var assign = __webpack_require__(19); var keyOf = __webpack_require__(20); var invariant = __webpack_require__(21); var hasOwnProperty = ({}).hasOwnProperty; function shallowCopy(x) { if (Array.isArray(x)) { return x.concat(); } else if (x && typeof x === 'object') { return assign(new x.constructor(), x); } else { return x; } } var COMMAND_PUSH = keyOf({ $push: null }); var COMMAND_UNSHIFT = keyOf({ $unshift: null }); var COMMAND_SPLICE = keyOf({ $splice: null }); var COMMAND_SET = keyOf({ $set: null }); var COMMAND_MERGE = keyOf({ $merge: null }); var COMMAND_APPLY = keyOf({ $apply: null }); var ALL_COMMANDS_LIST = [COMMAND_PUSH, COMMAND_UNSHIFT, COMMAND_SPLICE, COMMAND_SET, COMMAND_MERGE, COMMAND_APPLY]; var ALL_COMMANDS_SET = {}; ALL_COMMANDS_LIST.forEach(function (command) { ALL_COMMANDS_SET[command] = true; }); function invariantArrayCase(value, spec, command) { !Array.isArray(value) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected target of %s to be an array; got %s.', command, value) : invariant(false) : undefined; var specValue = spec[command]; !Array.isArray(specValue) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array; got %s. ' + 'Did you forget to wrap your parameter in an array?', command, specValue) : invariant(false) : undefined; } function update(value, spec) { !(typeof spec === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): You provided a key path to update() that did not contain one ' + 'of %s. Did you forget to include {%s: ...}?', ALL_COMMANDS_LIST.join(', '), COMMAND_SET) : invariant(false) : undefined; if (hasOwnProperty.call(spec, COMMAND_SET)) { !(Object.keys(spec).length === 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot have more than one key in an object with %s', COMMAND_SET) : invariant(false) : undefined; return spec[COMMAND_SET]; } var nextValue = shallowCopy(value); if (hasOwnProperty.call(spec, COMMAND_MERGE)) { var mergeObj = spec[COMMAND_MERGE]; !(mergeObj && typeof mergeObj === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): %s expects a spec of type \'object\'; got %s', COMMAND_MERGE, mergeObj) : invariant(false) : undefined; !(nextValue && typeof nextValue === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): %s expects a target of type \'object\'; got %s', COMMAND_MERGE, nextValue) : invariant(false) : undefined; assign(nextValue, spec[COMMAND_MERGE]); } if (hasOwnProperty.call(spec, COMMAND_PUSH)) { invariantArrayCase(value, spec, COMMAND_PUSH); spec[COMMAND_PUSH].forEach(function (item) { nextValue.push(item); }); } if (hasOwnProperty.call(spec, COMMAND_UNSHIFT)) { invariantArrayCase(value, spec, COMMAND_UNSHIFT); spec[COMMAND_UNSHIFT].forEach(function (item) { nextValue.unshift(item); }); } if (hasOwnProperty.call(spec, COMMAND_SPLICE)) { !Array.isArray(value) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected %s target to be an array; got %s', COMMAND_SPLICE, value) : invariant(false) : undefined; !Array.isArray(spec[COMMAND_SPLICE]) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array of arrays; got %s. ' + 'Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : invariant(false) : undefined; spec[COMMAND_SPLICE].forEach(function (args) { !Array.isArray(args) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array of arrays; got %s. ' + 'Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : invariant(false) : undefined; nextValue.splice.apply(nextValue, args); }); } if (hasOwnProperty.call(spec, COMMAND_APPLY)) { !(typeof spec[COMMAND_APPLY] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be a function; got %s.', COMMAND_APPLY, spec[COMMAND_APPLY]) : invariant(false) : undefined; nextValue = spec[COMMAND_APPLY](nextValue); } for (var k in spec) { if (!(ALL_COMMANDS_SET.hasOwnProperty(k) && ALL_COMMANDS_SET[k])) { nextValue[k] = update(value[k], spec[k]); } } return nextValue; } module.exports = update; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18))) /***/ }, /* 18 */ /***/ function(module, exports) { // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = setTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; clearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { setTimeout(drainQueue, 0); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }, /* 19 */ /***/ function(module, exports) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Object.assign */ // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign 'use strict'; function assign(target, sources) { if (target == null) { throw new TypeError('Object.assign target cannot be null or undefined'); } var to = Object(target); var hasOwnProperty = Object.prototype.hasOwnProperty; for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) { var nextSource = arguments[nextIndex]; if (nextSource == null) { continue; } var from = Object(nextSource); // We don't currently support accessors nor proxies. Therefore this // copy cannot throw. If we ever supported this then we must handle // exceptions and side-effects. We don't support symbols so they won't // be transferred. for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } } return to; } module.exports = assign; /***/ }, /* 20 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule keyOf */ /** * Allows extraction of a minified key. Let's the build system minify keys * without losing the ability to dynamically use key strings as values * themselves. Pass in an object with a single key/val pair and it will return * you the string key of that single record. Suppose you want to grab the * value for a key 'className' inside of an object. Key/val minification may * have aliased that key to be 'xa12'. keyOf({className: null}) will return * 'xa12' in that case. Resolve keys you want to use once at startup time, then * reuse those resolutions. */ "use strict"; var keyOf = function (oneKeyObj) { var key; for (key in oneKeyObj) { if (!oneKeyObj.hasOwnProperty(key)) { continue; } return key; } return null; }; module.exports = keyOf; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule invariant */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ function invariant(condition, format, a, b, c, d, e, f) { if (process.env.NODE_ENV !== 'production') { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } module.exports = invariant; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18))) /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.jQuery = exports.animation = undefined; var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _reactAddonsUpdate = __webpack_require__(16); var _reactAddonsUpdate2 = _interopRequireDefault(_reactAddonsUpdate); var _classnames = __webpack_require__(6); var _classnames2 = _interopRequireDefault(_classnames); var _animationMixin = __webpack_require__(23); var _animationMixin2 = _interopRequireDefault(_animationMixin); var _jQueryMixin = __webpack_require__(28); var _jQueryMixin2 = _interopRequireDefault(_jQueryMixin); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function noop() {} var ToastMessageSpec = { displayName: "ToastMessage", getDefaultProps: function getDefaultProps() { var iconClassNames = { error: "toast-error", info: "toast-info", success: "toast-success", warning: "toast-warning" }; return { className: "toast", iconClassNames: iconClassNames, titleClassName: "toast-title", messageClassName: "toast-message", tapToDismiss: true, closeButton: false }; }, handleOnClick: function handleOnClick(event) { this.props.handleOnClick(event); if (this.props.tapToDismiss) { this.hideToast(true); } }, _handle_close_button_click: function _handle_close_button_click(event) { event.stopPropagation(); this.hideToast(true); }, _handle_remove: function _handle_remove() { this.props.handleRemove(this.props.toastId); }, _render_close_button: function _render_close_button() { return this.props.closeButton ? _react2.default.createElement("button", { className: "toast-close-button", role: "button", onClick: this._handle_close_button_click, dangerouslySetInnerHTML: { __html: "&times;" } }) : false; }, _render_title_element: function _render_title_element() { return this.props.title ? _react2.default.createElement( "div", { className: this.props.titleClassName }, this.props.title ) : false; }, _render_message_element: function _render_message_element() { return this.props.message ? _react2.default.createElement( "div", { className: this.props.messageClassName }, this.props.message ) : false; }, render: function render() { var iconClassName = this.props.iconClassName || this.props.iconClassNames[this.props.type]; return _react2.default.createElement( "div", { className: (0, _classnames2.default)(this.props.className, iconClassName), style: this.props.style, onClick: this.handleOnClick, onMouseEnter: this.handleMouseEnter, onMouseLeave: this.handleMouseLeave }, this._render_close_button(), this._render_title_element(), this._render_message_element() ); } }; var animation = exports.animation = _react2.default.createClass((0, _reactAddonsUpdate2.default)(ToastMessageSpec, { displayName: { $set: "ToastMessage.animation" }, mixins: { $set: [_animationMixin2.default] } })); var jQuery = exports.jQuery = _react2.default.createClass((0, _reactAddonsUpdate2.default)(ToastMessageSpec, { displayName: { $set: "ToastMessage.jQuery" }, mixins: { $set: [_jQueryMixin2.default] } })); /* * assign default noop functions */ ToastMessageSpec.handleMouseEnter = noop; ToastMessageSpec.handleMouseLeave = noop; ToastMessageSpec.hideToast = noop; var ToastMessage = _react2.default.createClass(ToastMessageSpec); ToastMessage.animation = animation; ToastMessage.jQuery = jQuery; exports.default = ToastMessage; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _CSSCore = __webpack_require__(24); var _CSSCore2 = _interopRequireDefault(_CSSCore); var _ReactTransitionEvents = __webpack_require__(26); var _ReactTransitionEvents2 = _interopRequireDefault(_ReactTransitionEvents); var _reactDom = __webpack_require__(5); var _reactDom2 = _interopRequireDefault(_reactDom); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var TICK = 17; var toString = Object.prototype.toString; exports.default = { getDefaultProps: function getDefaultProps() { return { transition: null, // some examples defined in index.scss (scale, fadeInOut, rotate) showAnimation: "animated bounceIn", // or other animations from animate.css hideAnimation: "animated bounceOut", timeOut: 5000, extendedTimeOut: 1000 }; }, componentWillMount: function componentWillMount() { this.classNameQueue = []; this.isHiding = false; this.intervalId = null; }, componentDidMount: function componentDidMount() { var _this = this; this._is_mounted = true; this._show(); var node = _reactDom2.default.findDOMNode(this); var onHideComplete = function onHideComplete() { if (_this.isHiding) { _this._set_is_hiding(false); _ReactTransitionEvents2.default.removeEndEventListener(node, onHideComplete); _this._handle_remove(); } }; _ReactTransitionEvents2.default.addEndEventListener(node, onHideComplete); if (this.props.timeOut > 0) { this._set_interval_id(setTimeout(this.hideToast, this.props.timeOut)); } }, componentWillUnmount: function componentWillUnmount() { this._is_mounted = false; if (this.intervalId) { clearTimeout(this.intervalId); } }, _set_transition: function _set_transition(hide) { var animationType = hide ? "leave" : "enter"; var node = _reactDom2.default.findDOMNode(this); var className = this.props.transition + "-" + animationType; var activeClassName = className + "-active"; var endListener = function endListener(e) { if (e && e.target !== node) { return; } _CSSCore2.default.removeClass(node, className); _CSSCore2.default.removeClass(node, activeClassName); _ReactTransitionEvents2.default.removeEndEventListener(node, endListener); }; _ReactTransitionEvents2.default.addEndEventListener(node, endListener); _CSSCore2.default.addClass(node, className); // Need to do this to actually trigger a transition. this._queue_class(activeClassName); }, _clear_transition: function _clear_transition(hide) { var node = _reactDom2.default.findDOMNode(this); var animationType = hide ? "leave" : "enter"; var className = this.props.transition + "-" + animationType; var activeClassName = className + "-active"; _CSSCore2.default.removeClass(node, className); _CSSCore2.default.removeClass(node, activeClassName); }, _set_animation: function _set_animation(hide) { var node = _reactDom2.default.findDOMNode(this); var animations = this._get_animation_classes(hide); var endListener = function endListener(e) { if (e && e.target !== node) { return; } animations.forEach(function (anim) { _CSSCore2.default.removeClass(node, anim); }); _ReactTransitionEvents2.default.removeEndEventListener(node, endListener); }; _ReactTransitionEvents2.default.addEndEventListener(node, endListener); animations.forEach(function (anim) { _CSSCore2.default.addClass(node, anim); }); }, _get_animation_classes: function _get_animation_classes(hide) { var animations = hide ? this.props.hideAnimation : this.props.showAnimation; if ("[object Array]" === toString.call(animations)) { return animations; } else if ("string" === typeof animations) { return animations.split(" "); } }, _clear_animation: function _clear_animation(hide) { var _this2 = this; var animations = this._get_animation_classes(hide); animations.forEach(function (animation) { _CSSCore2.default.removeClass(_reactDom2.default.findDOMNode(_this2), animation); }); }, _queue_class: function _queue_class(className) { this.classNameQueue.push(className); if (!this.timeout) { this.timeout = setTimeout(this._flush_class_name_queue, TICK); } }, _flush_class_name_queue: function _flush_class_name_queue() { if (this._is_mounted) { this.classNameQueue.forEach(_CSSCore2.default.addClass.bind(_CSSCore2.default, _reactDom2.default.findDOMNode(this))); } this.classNameQueue.length = 0; this.timeout = null; }, _show: function _show() { if (this.props.transition) { this._set_transition(); } else if (this.props.showAnimation) { this._set_animation(); } }, handleMouseEnter: function handleMouseEnter() { clearTimeout(this.intervalId); this._set_interval_id(null); if (this.isHiding) { this._set_is_hiding(false); if (this.props.hideAnimation) { this._clear_animation(true); } else if (this.props.transition) { this._clear_transition(true); } } }, handleMouseLeave: function handleMouseLeave() { if (!this.isHiding && (this.props.timeOut > 0 || this.props.extendedTimeOut > 0)) { this._set_interval_id(setTimeout(this.hideToast, this.props.extendedTimeOut)); } }, hideToast: function hideToast(override) { if (this.isHiding || this.intervalId === null && !override) { return; } this._set_is_hiding(true); if (this.props.transition) { this._set_transition(true); } else if (this.props.hideAnimation) { this._set_animation(true); } else { this._handle_remove(); } }, _set_interval_id: function _set_interval_id(intervalId) { this.intervalId = intervalId; }, _set_is_hiding: function _set_is_hiding(isHiding) { this.isHiding = isHiding; } }; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CSSCore * @typechecks */ 'use strict'; var invariant = __webpack_require__(25); /** * The CSSCore module specifies the API (and implements most of the methods) * that should be used when dealing with the display of elements (via their * CSS classes and visibility on screen. It is an API focused on mutating the * display and not reading it as no logical state should be encoded in the * display of elements. */ var CSSCore = { /** * Adds the class passed in to the element if it doesn't already have it. * * @param {DOMElement} element the element to set the class on * @param {string} className the CSS className * @return {DOMElement} the element passed in */ addClass: function (element, className) { !!/\s/.test(className) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'CSSCore.addClass takes only a single class name. "%s" contains ' + 'multiple classes.', className) : invariant(false) : undefined; if (className) { if (element.classList) { element.classList.add(className); } else if (!CSSCore.hasClass(element, className)) { element.className = element.className + ' ' + className; } } return element; }, /** * Removes the class passed in from the element * * @param {DOMElement} element the element to set the class on * @param {string} className the CSS className * @return {DOMElement} the element passed in */ removeClass: function (element, className) { !!/\s/.test(className) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'CSSCore.removeClass takes only a single class name. "%s" contains ' + 'multiple classes.', className) : invariant(false) : undefined; if (className) { if (element.classList) { element.classList.remove(className); } else if (CSSCore.hasClass(element, className)) { element.className = element.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)', 'g'), '$1').replace(/\s+/g, ' ') // multiple spaces to one .replace(/^\s*|\s*$/g, ''); // trim the ends } } return element; }, /** * Helper to add or remove a class from an element based on a condition. * * @param {DOMElement} element the element to set the class on * @param {string} className the CSS className * @param {*} bool condition to whether to add or remove the class * @return {DOMElement} the element passed in */ conditionClass: function (element, className, bool) { return (bool ? CSSCore.addClass : CSSCore.removeClass)(element, className); }, /** * Tests whether the element has the class specified. * * @param {DOMNode|DOMWindow} element the element to set the class on * @param {string} className the CSS className * @return {boolean} true if the element has the class, false if not */ hasClass: function (element, className) { !!/\s/.test(className) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'CSS.hasClass takes only a single class name.') : invariant(false) : undefined; if (element.classList) { return !!className && element.classList.contains(className); } return (' ' + element.className + ' ').indexOf(' ' + className + ' ') > -1; } }; module.exports = CSSCore; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18))) /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule invariant */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ function invariant(condition, format, a, b, c, d, e, f) { if (process.env.NODE_ENV !== 'production') { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } module.exports = invariant; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18))) /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactTransitionEvents */ 'use strict'; var ExecutionEnvironment = __webpack_require__(27); /** * EVENT_NAME_MAP is used to determine which event fired when a * transition/animation ends, based on the style property used to * define that event. */ var EVENT_NAME_MAP = { transitionend: { 'transition': 'transitionend', 'WebkitTransition': 'webkitTransitionEnd', 'MozTransition': 'mozTransitionEnd', 'OTransition': 'oTransitionEnd', 'msTransition': 'MSTransitionEnd' }, animationend: { 'animation': 'animationend', 'WebkitAnimation': 'webkitAnimationEnd', 'MozAnimation': 'mozAnimationEnd', 'OAnimation': 'oAnimationEnd', 'msAnimation': 'MSAnimationEnd' } }; var endEvents = []; function detectEvents() { var testEl = document.createElement('div'); var style = testEl.style; // On some platforms, in particular some releases of Android 4.x, // the un-prefixed "animation" and "transition" properties are defined on the // style object but the events that fire will still be prefixed, so we need // to check if the un-prefixed events are useable, and if not remove them // from the map if (!('AnimationEvent' in window)) { delete EVENT_NAME_MAP.animationend.animation; } if (!('TransitionEvent' in window)) { delete EVENT_NAME_MAP.transitionend.transition; } for (var baseEventName in EVENT_NAME_MAP) { var baseEvents = EVENT_NAME_MAP[baseEventName]; for (var styleName in baseEvents) { if (styleName in style) { endEvents.push(baseEvents[styleName]); break; } } } } if (ExecutionEnvironment.canUseDOM) { detectEvents(); } // We use the raw {add|remove}EventListener() call because EventListener // does not know how to remove event listeners and we really should // clean up. Also, these events are not triggered in older browsers // so we should be A-OK here. function addEventListener(node, eventName, eventListener) { node.addEventListener(eventName, eventListener, false); } function removeEventListener(node, eventName, eventListener) { node.removeEventListener(eventName, eventListener, false); } var ReactTransitionEvents = { addEndEventListener: function (node, eventListener) { if (endEvents.length === 0) { // If CSS transitions are not supported, trigger an "end animation" // event immediately. window.setTimeout(eventListener, 0); return; } endEvents.forEach(function (endEvent) { addEventListener(node, endEvent, eventListener); }); }, removeEndEventListener: function (node, eventListener) { if (endEvents.length === 0) { return; } endEvents.forEach(function (endEvent) { removeEventListener(node, endEvent, eventListener); }); } }; module.exports = ReactTransitionEvents; /***/ }, /* 27 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ExecutionEnvironment */ 'use strict'; var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); /** * Simple, lightweight module assisting with the detection and context of * Worker. Helps avoid circular dependencies and allows code to reason about * whether or not they are in a Worker, even if they never include the main * `ReactWorker` dependency. */ var ExecutionEnvironment = { canUseDOM: canUseDOM, canUseWorkers: typeof Worker !== 'undefined', canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent), canUseViewport: canUseDOM && !!window.screen, isInWorker: !canUseDOM // For now, this is true - might change in the future. }; module.exports = ExecutionEnvironment; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _reactDom = __webpack_require__(5); var _reactDom2 = _interopRequireDefault(_reactDom); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function call_show_method($node, props) { $node[props.showMethod]({ duration: props.showDuration, easing: props.showEasing }); } exports.default = { getDefaultProps: function getDefaultProps() { return { style: { display: "none" }, // effective $.hide() showMethod: "fadeIn", // slideDown, and show are built into jQuery showDuration: 300, showEasing: "swing", // and linear are built into jQuery hideMethod: "fadeOut", hideDuration: 1000, hideEasing: "swing", // timeOut: 5000, extendedTimeOut: 1000 }; }, getInitialState: function getInitialState() { return { intervalId: null, isHiding: false }; }, componentDidMount: function componentDidMount() { call_show_method(this._get_$_node(), this.props); if (this.props.timeOut > 0) { this._set_interval_id(setTimeout(this.hideToast, this.props.timeOut)); } }, handleMouseEnter: function handleMouseEnter() { clearTimeout(this.state.intervalId); this._set_interval_id(null); this._set_is_hiding(false); call_show_method(this._get_$_node().stop(true, true), this.props); }, handleMouseLeave: function handleMouseLeave() { if (!this.state.isHiding && (this.props.timeOut > 0 || this.props.extendedTimeOut > 0)) { this._set_interval_id(setTimeout(this.hideToast, this.props.extendedTimeOut)); } }, hideToast: function hideToast(override) { if (this.state.isHiding || this.state.intervalId === null && !override) { return; } this.setState({ isHiding: true }); this._get_$_node()[this.props.hideMethod]({ duration: this.props.hideDuration, easing: this.props.hideEasing, complete: this._handle_remove }); }, _get_$_node: function _get_$_node() { /* eslint-disable no-undef */ return jQuery(_reactDom2.default.findDOMNode(this)); /* eslint-enable no-undef */ }, _set_interval_id: function _set_interval_id(intervalId) { this.setState({ intervalId: intervalId }); }, _set_is_hiding: function _set_is_hiding(isHiding) { this.setState({ isHiding: isHiding }); } }; /***/ }, /* 29 */ /***/ 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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _PageButtonJs = __webpack_require__(30); var _PageButtonJs2 = _interopRequireDefault(_PageButtonJs); var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var PaginationList = (function (_Component) { _inherits(PaginationList, _Component); function PaginationList() { var _this = this; _classCallCheck(this, PaginationList); _get(Object.getPrototypeOf(PaginationList.prototype), 'constructor', this).apply(this, arguments); this.changePage = function (page) { var _props = _this.props; var prePage = _props.prePage; var currPage = _props.currPage; var nextPage = _props.nextPage; var lastPage = _props.lastPage; var firstPage = _props.firstPage; var sizePerPage = _props.sizePerPage; if (page === prePage) { page = currPage - 1 < 1 ? 1 : currPage - 1; } else if (page === nextPage) { page = currPage + 1 > _this.totalPages ? _this.totalPages : currPage + 1; } else if (page === lastPage) { page = _this.totalPages; } else if (page === firstPage) { page = 1; } else { page = parseInt(page, 10); } if (page !== currPage) { _this.props.changePage(page, sizePerPage); } }; this.changeSizePerPage = function (e) { e.preventDefault(); var selectSize = parseInt(e.currentTarget.text, 10); var currPage = _this.props.currPage; if (selectSize !== _this.props.sizePerPage) { _this.totalPages = Math.ceil(_this.props.dataSize / selectSize); if (currPage > _this.totalPages) currPage = _this.totalPages; _this.props.changePage(currPage, selectSize); if (_this.props.onSizePerPageList) { _this.props.onSizePerPageList(selectSize); } } }; } _createClass(PaginationList, [{ key: 'render', value: function render() { var _this2 = this; var _props2 = this.props; var dataSize = _props2.dataSize; var sizePerPage = _props2.sizePerPage; var sizePerPageList = _props2.sizePerPageList; this.totalPages = Math.ceil(dataSize / sizePerPage); var pageBtns = this.makePage(); var pageListStyle = { float: 'right', // override the margin-top defined in .pagination class in bootstrap. marginTop: '0px' }; var sizePerPageOptions = sizePerPageList.map(function (_sizePerPage) { return _react2['default'].createElement( 'li', { key: _sizePerPage, role: 'presentation' }, _react2['default'].createElement( 'a', { role: 'menuitem', tabIndex: '-1', href: '#', onClick: _this2.changeSizePerPage }, _sizePerPage ) ); }); return _react2['default'].createElement( 'div', { className: 'row', style: { marginTop: 15 } }, sizePerPageList.length > 1 ? _react2['default'].createElement( 'div', null, _react2['default'].createElement( 'div', { className: 'col-md-6' }, _react2['default'].createElement( 'div', { className: 'dropdown' }, _react2['default'].createElement( 'button', { className: 'btn btn-default dropdown-toggle', type: 'button', id: 'pageDropDown', 'data-toggle': 'dropdown', 'aria-expanded': 'true' }, sizePerPage, _react2['default'].createElement( 'span', null, ' ', _react2['default'].createElement('span', { className: 'caret' }) ) ), _react2['default'].createElement( 'ul', { className: 'dropdown-menu', role: 'menu', 'aria-labelledby': 'pageDropDown' }, sizePerPageOptions ) ) ), _react2['default'].createElement( 'div', { className: 'col-md-6' }, _react2['default'].createElement( 'ul', { className: 'pagination', style: pageListStyle }, pageBtns ) ) ) : _react2['default'].createElement( 'div', { className: 'col-md-12' }, _react2['default'].createElement( 'ul', { className: 'pagination', style: pageListStyle }, pageBtns ) ) ); } }, { key: 'makePage', value: function makePage() { var pages = this.getPages(); return pages.map(function (page) { var isActive = page === this.props.currPage; var disabled = false; var hidden = false; if (this.props.currPage === 1 && (page === this.props.firstPage || page === this.props.prePage)) { disabled = true; hidden = true; } if (this.props.currPage === this.totalPages && (page === this.props.nextPage || page === this.props.lastPage)) { disabled = true; hidden = true; } return _react2['default'].createElement( _PageButtonJs2['default'], { key: page, changePage: this.changePage, active: isActive, disable: disabled, hidden: hidden }, page ); }, this); } }, { key: 'getPages', value: function getPages() { var pages = undefined; var startPage = 1; var endPage = this.totalPages; startPage = Math.max(this.props.currPage - Math.floor(this.props.paginationSize / 2), 1); endPage = startPage + this.props.paginationSize - 1; if (endPage > this.totalPages) { endPage = this.totalPages; startPage = endPage - this.props.paginationSize + 1; } if (startPage !== 1 && this.totalPages > this.props.paginationSize) { pages = [this.props.firstPage, this.props.prePage]; } else if (this.totalPages > 1) { pages = [this.props.prePage]; } else { pages = []; } for (var i = startPage; i <= endPage; i++) { if (i > 0) pages.push(i); } if (endPage !== this.totalPages) { pages.push(this.props.nextPage); pages.push(this.props.lastPage); } else if (this.totalPages > 1) { pages.push(this.props.nextPage); } return pages; } }]); return PaginationList; })(_react.Component); PaginationList.propTypes = { currPage: _react.PropTypes.number, sizePerPage: _react.PropTypes.number, dataSize: _react.PropTypes.number, changePage: _react.PropTypes.func, sizePerPageList: _react.PropTypes.array, paginationSize: _react.PropTypes.number, remote: _react.PropTypes.bool, onSizePerPageList: _react.PropTypes.func, prePage: _react.PropTypes.string }; PaginationList.defaultProps = { sizePerPage: _Const2['default'].SIZE_PER_PAGE }; exports['default'] = PaginationList; module.exports = exports['default']; /***/ }, /* 30 */ /***/ 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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(6); var _classnames2 = _interopRequireDefault(_classnames); var PageButton = (function (_Component) { _inherits(PageButton, _Component); function PageButton(props) { var _this = this; _classCallCheck(this, PageButton); _get(Object.getPrototypeOf(PageButton.prototype), 'constructor', this).call(this, props); this.pageBtnClick = function (e) { e.preventDefault(); _this.props.changePage(e.currentTarget.textContent); }; } _createClass(PageButton, [{ key: 'render', value: function render() { var classes = (0, _classnames2['default'])({ 'active': this.props.active, 'disabled': this.props.disable, 'hidden': this.props.hidden }); return _react2['default'].createElement( 'li', { className: classes }, _react2['default'].createElement( 'a', { href: '#', onClick: this.pageBtnClick }, this.props.children ) ); } }]); return PageButton; })(_react.Component); PageButton.propTypes = { changePage: _react.PropTypes.func, active: _react.PropTypes.bool, disable: _react.PropTypes.bool, hidden: _react.PropTypes.bool, children: _react.PropTypes.node }; exports['default'] = PageButton; module.exports = exports['default']; /***/ }, /* 31 */ /***/ 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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(6); var _classnames2 = _interopRequireDefault(_classnames); var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var _Editor = __webpack_require__(12); var _Editor2 = _interopRequireDefault(_Editor); var _NotificationJs = __webpack_require__(13); var _NotificationJs2 = _interopRequireDefault(_NotificationJs); var ToolBar = (function (_Component) { _inherits(ToolBar, _Component); function ToolBar(props) { var _this = this; _classCallCheck(this, ToolBar); _get(Object.getPrototypeOf(ToolBar.prototype), 'constructor', this).call(this, props); this.handleSaveBtnClick = function () { var newObj = _this.checkAndParseForm(); if (!newObj) { // validate errors return; } var msg = _this.props.onAddRow(newObj); if (msg) { _this.refs.notifier.notice('error', msg, 'Pressed ESC can cancel'); _this.clearTimeout(); // shake form and hack prevent modal hide _this.setState({ shakeEditor: true, validateState: 'this is hack for prevent bootstrap modal hide' }); // clear animate class _this.timeouteClear = setTimeout(function () { _this.setState({ shakeEditor: false }); }, 300); } else { // reset state and hide modal hide _this.setState({ validateState: null, shakeEditor: false }, function () { document.querySelector('.modal-backdrop').click(); document.querySelector('.' + _this.modalClassName).click(); }); // reset form _this.refs.form.reset(); } }; this.handleShowOnlyToggle = function () { _this.setState({ showSelected: !_this.state.showSelected }); _this.props.onShowOnlySelected(); }; this.handleDropRowBtnClick = function () { _this.props.onDropRow(); }; this.handleKeyUp = function (e) { _this.props.onSearch(e.currentTarget.value); }; this.handleExportCSV = function () { _this.props.onExportCSV(); }; this.handleClearBtnClick = function () { _this.refs.seachInput.value = ''; _this.props.onSearch(''); }; this.timeouteClear = 0; this.modalClassName; this.state = { isInsertRowTrigger: true, validateState: null, shakeEditor: false, showSelected: false }; } _createClass(ToolBar, [{ key: 'componentWillUnmount', value: function componentWillUnmount() { this.clearTimeout(); } }, { key: 'clearTimeout', value: (function (_clearTimeout) { function clearTimeout() { return _clearTimeout.apply(this, arguments); } clearTimeout.toString = function () { return _clearTimeout.toString(); }; return clearTimeout; })(function () { if (this.timeouteClear) { clearTimeout(this.timeouteClear); this.timeouteClear = 0; } }) }, { key: 'checkAndParseForm', value: function checkAndParseForm() { var _this2 = this; var newObj = {}; var validateState = {}; var isValid = true; var tempValue = undefined; var tempMsg = undefined; this.props.columns.forEach(function (column, i) { if (column.autoValue) { // when you want same auto generate value and not allow edit, example ID field var time = new Date().getTime(); tempValue = typeof column.autoValue === 'function' ? column.autoValue() : 'autovalue-' + time; } else { var dom = this.refs[column.field + i]; tempValue = dom.value; if (column.editable && column.editable.type === 'checkbox') { var values = tempValue.split(':'); tempValue = dom.checked ? values[0] : values[1]; } if (column.editable && column.editable.validator) { // process validate tempMsg = column.editable.validator(tempValue); if (tempMsg !== true) { isValid = false; validateState[column.field] = tempMsg; } } } newObj[column.field] = tempValue; }, this); if (isValid) { return newObj; } else { this.clearTimeout(); // show error in form and shake it this.setState({ validateState: validateState, shakeEditor: true }); // notifier error this.refs.notifier.notice('error', 'Form validate errors, please checking!', 'Pressed ESC can cancel'); // clear animate class this.timeouteClear = setTimeout(function () { _this2.setState({ shakeEditor: false }); }, 300); return null; } } }, { key: 'handleCloseBtn', value: function handleCloseBtn() { this.refs.warning.style.display = 'none'; } }, { key: 'render', value: function render() { this.modalClassName = 'bs-table-modal-sm' + new Date().getTime(); var insertBtn = null; var deleteBtn = null; var exportCSV = null; var showSelectedOnlyBtn = null; if (this.props.enableInsert) { insertBtn = _react2['default'].createElement( 'button', { type: 'button', className: 'btn btn-info react-bs-table-add-btn', 'data-toggle': 'modal', 'data-target': '.' + this.modalClassName }, _react2['default'].createElement('i', { className: 'glyphicon glyphicon-plus' }), ' New' ); } if (this.props.enableDelete) { deleteBtn = _react2['default'].createElement( 'button', { type: 'button', className: 'btn btn-warning react-bs-table-del-btn', 'data-toggle': 'tooltip', 'data-placement': 'right', title: 'Drop selected row', onClick: this.handleDropRowBtnClick }, _react2['default'].createElement('i', { className: 'glyphicon glyphicon-trash' }), ' Delete' ); } if (this.props.enableShowOnlySelected) { showSelectedOnlyBtn = _react2['default'].createElement( 'button', { type: 'button', onClick: this.handleShowOnlyToggle, className: 'btn btn-primary', 'data-toggle': 'button', 'aria-pressed': 'false' }, this.state.showSelected ? _Const2['default'].SHOW_ALL : _Const2['default'].SHOW_ONLY_SELECT ); } if (this.props.enableExportCSV) { exportCSV = _react2['default'].createElement( 'button', { type: 'button', className: 'btn btn-success', onClick: this.handleExportCSV }, _react2['default'].createElement('i', { className: 'glyphicon glyphicon-export' }), ' Export to CSV' ); } var searchTextInput = this.renderSearchPanel(); var modal = this.props.enableInsert ? this.renderInsertRowModal() : null; return _react2['default'].createElement( 'div', { className: 'row' }, _react2['default'].createElement( 'div', { className: 'col-xs-12 col-sm-6 col-md-6 col-lg-8' }, _react2['default'].createElement( 'div', { className: 'btn-group btn-group-sm', role: 'group' }, exportCSV, insertBtn, deleteBtn, showSelectedOnlyBtn ) ), _react2['default'].createElement( 'div', { className: 'col-xs-12 col-sm-6 col-md-6 col-lg-4' }, searchTextInput ), _react2['default'].createElement(_NotificationJs2['default'], { ref: 'notifier' }), modal ); } }, { key: 'renderSearchPanel', value: function renderSearchPanel() { if (this.props.enableSearch) { var classNames = 'form-group form-group-sm react-bs-table-search-form'; var clearBtn = null; if (this.props.clearSearch) { clearBtn = _react2['default'].createElement( 'span', { className: 'input-group-btn' }, _react2['default'].createElement( 'button', { className: 'btn btn-default', type: 'button', onClick: this.handleClearBtnClick }, 'Clear' ) ); classNames += ' input-group input-group-sm'; } return _react2['default'].createElement( 'div', { className: classNames }, _react2['default'].createElement('input', { ref: 'seachInput', className: 'form-control', type: 'text', placeholder: this.props.searchPlaceholder ? this.props.searchPlaceholder : 'Search', onKeyUp: this.handleKeyUp }), clearBtn ); } else { return null; } } }, { key: 'renderInsertRowModal', value: function renderInsertRowModal() { var validateState = this.state.validateState || {}; var shakeEditor = this.state.shakeEditor; var inputField = this.props.columns.map(function (column, i) { var editable = column.editable; var format = column.format; var field = column.field; var name = column.name; var autoValue = column.autoValue; var attr = { ref: field + i, placeholder: editable.placeholder ? editable.placeholder : name }; if (autoValue) { // when you want same auto generate value // and not allow edit, for example ID field return null; } var error = validateState[field] ? _react2['default'].createElement( 'span', { className: 'help-block bg-danger' }, validateState[field] ) : null; // let editor = Editor(editable,attr,format); // if(editor.props.type && editor.props.type == 'checkbox'){ return _react2['default'].createElement( 'div', { className: 'form-group', key: field }, _react2['default'].createElement( 'label', null, name ), (0, _Editor2['default'])(editable, attr, format, ''), error ); }); var modalClass = (0, _classnames2['default'])('modal', 'fade', this.modalClassName, { // hack prevent bootstrap modal hide by reRender 'in': shakeEditor || this.state.validateState }); var dialogClass = (0, _classnames2['default'])('modal-dialog', 'modal-sm', { 'animated': shakeEditor, 'shake': shakeEditor }); return _react2['default'].createElement( 'div', { ref: 'modal', className: modalClass, tabIndex: '-1', role: 'dialog' }, _react2['default'].createElement( 'div', { className: dialogClass }, _react2['default'].createElement( 'div', { className: 'modal-content' }, _react2['default'].createElement( 'div', { className: 'modal-header' }, _react2['default'].createElement( 'button', { type: 'button', className: 'close', 'data-dismiss': 'modal', 'aria-label': 'Close' }, _react2['default'].createElement( 'span', { 'aria-hidden': 'true' }, '×' ) ), _react2['default'].createElement( 'h4', { className: 'modal-title' }, 'New Record' ) ), _react2['default'].createElement( 'div', { className: 'modal-body' }, _react2['default'].createElement( 'form', { ref: 'form' }, inputField ) ), _react2['default'].createElement( 'div', { className: 'modal-footer' }, _react2['default'].createElement( 'button', { type: 'button', className: 'btn btn-default', 'data-dismiss': 'modal' }, 'Close' ), _react2['default'].createElement( 'button', { type: 'button', className: 'btn btn-info', onClick: this.handleSaveBtnClick }, 'Save' ) ) ) ) ); } }]); return ToolBar; })(_react.Component); ToolBar.propTypes = { onAddRow: _react.PropTypes.func, onDropRow: _react.PropTypes.func, onShowOnlySelected: _react.PropTypes.func, enableInsert: _react.PropTypes.bool, enableDelete: _react.PropTypes.bool, enableSearch: _react.PropTypes.bool, enableShowOnlySelected: _react.PropTypes.bool, columns: _react.PropTypes.array, searchPlaceholder: _react.PropTypes.string, clearSearch: _react.PropTypes.bool }; ToolBar.defaultProps = { enableInsert: false, enableDelete: false, enableSearch: false, enableShowOnlySelected: false, clearSearch: false }; exports['default'] = ToolBar; module.exports = exports['default']; /***/ }, /* 32 */ /***/ 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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var _classnames = __webpack_require__(6); var _classnames2 = _interopRequireDefault(_classnames); var TableFilter = (function (_Component) { _inherits(TableFilter, _Component); function TableFilter(props) { var _this = this; _classCallCheck(this, TableFilter); _get(Object.getPrototypeOf(TableFilter.prototype), 'constructor', this).call(this, props); this.handleKeyUp = function (e) { var _e$currentTarget = e.currentTarget; var value = _e$currentTarget.value; var name = _e$currentTarget.name; if (value.trim() === '') { delete _this.filterObj[name]; } else { _this.filterObj[name] = value; } _this.props.onFilter(_this.filterObj); }; this.filterObj = {}; } _createClass(TableFilter, [{ key: 'render', value: function render() { var _props = this.props; var striped = _props.striped; var condensed = _props.condensed; var rowSelectType = _props.rowSelectType; var columns = _props.columns; var tableClasses = (0, _classnames2['default'])('table', { 'table-striped': striped, 'table-condensed': condensed }); var selectRowHeader = null; if (rowSelectType === _Const2['default'].ROW_SELECT_SINGLE || rowSelectType === _Const2['default'].ROW_SELECT_MULTI) { var style = { width: 35, paddingLeft: 0, paddingRight: 0 }; selectRowHeader = _react2['default'].createElement( 'th', { style: style, key: -1 }, 'Filter' ); } var filterField = columns.map(function (column) { var hidden = column.hidden; var width = column.width; var name = column.name; var thStyle = { display: hidden ? 'none' : null, width: width }; return _react2['default'].createElement( 'th', { key: name, style: thStyle }, _react2['default'].createElement( 'div', { className: 'th-inner table-header-column' }, _react2['default'].createElement('input', { size: '10', type: 'text', placeholder: name, name: name, onKeyUp: this.handleKeyUp }) ) ); }, this); return _react2['default'].createElement( 'table', { className: tableClasses, style: { marginTop: 5 } }, _react2['default'].createElement( 'thead', null, _react2['default'].createElement( 'tr', { style: { borderBottomStyle: 'hidden' } }, selectRowHeader, filterField ) ) ); } }]); return TableFilter; })(_react.Component); TableFilter.propTypes = { columns: _react.PropTypes.array, rowSelectType: _react.PropTypes.string, onFilter: _react.PropTypes.func }; exports['default'] = TableFilter; module.exports = exports['default']; /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { /* eslint no-nested-ternary: 0 */ /* eslint guard-for-in: 0 */ /* eslint no-console: 0 */ /* eslint eqeqeq: 0 */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var EventEmitter = __webpack_require__(34).EventEmitter; function _sort(arr, sortField, order, sortFunc) { order = order.toLowerCase(); arr.sort(function (a, b) { if (sortFunc) { return sortFunc(a, b, order, sortField); } else { if (order === _Const2['default'].SORT_DESC) { return a[sortField] > b[sortField] ? -1 : a[sortField] < b[sortField] ? 1 : 0; } else { return a[sortField] < b[sortField] ? -1 : a[sortField] > b[sortField] ? 1 : 0; } } }); return arr; } var TableDataSet = (function (_EventEmitter) { _inherits(TableDataSet, _EventEmitter); function TableDataSet(data) { _classCallCheck(this, TableDataSet); _get(Object.getPrototypeOf(TableDataSet.prototype), 'constructor', this).call(this, data); this.data = data; } _createClass(TableDataSet, [{ key: 'setData', value: function setData(data) { this.emit('change', data); } }, { key: 'clear', value: function clear() { this.data = null; } }, { key: 'getData', value: function getData() { return this.data; } }]); return TableDataSet; })(EventEmitter); exports.TableDataSet = TableDataSet; var TableDataStore = (function () { function TableDataStore(data) { _classCallCheck(this, TableDataStore); this.data = data; this.colInfos = null; this.filteredData = null; this.isOnFilter = false; this.filterObj = null; this.searchText = null; this.sortObj = null; this.pageObj = {}; this.selected = []; this.multiColumnSearch = false; this.showOnlySelected = false; this.remote = false; // remote data } _createClass(TableDataStore, [{ key: 'setProps', value: function setProps(props) { this.keyField = props.keyField; this.enablePagination = props.isPagination; this.colInfos = props.colInfos; this.remote = props.remote; this.multiColumnSearch = props.multiColumnSearch; } }, { key: 'setData', value: function setData(data) { this.data = data; if (this.isOnFilter) { if (this.filterObj !== null) this.filter(this.filterObj); if (this.searchText !== null) this.search(this.searchText); } if (this.sortObj) { this.sort(this.sortObj.order, this.sortObj.sortField); } } }, { key: 'getSortInfo', value: function getSortInfo() { return this.sortObj; } }, { key: 'setSelectedRowKey', value: function setSelectedRowKey(selectedRowKeys) { this.selected = selectedRowKeys; } }, { key: 'getSelectedRowKeys', value: function getSelectedRowKeys() { return this.selected; } }, { key: 'getCurrentDisplayData', value: function getCurrentDisplayData() { if (this.isOnFilter) return this.filteredData;else return this.data; } }, { key: 'ignoreNonSelected', value: function ignoreNonSelected() { var _this = this; this.showOnlySelected = !this.showOnlySelected; if (this.showOnlySelected) { this.isOnFilter = true; this.filteredData = this.data.filter(function (row) { var result = _this.selected.find(function (x) { return row[_this.keyField] === x; }); return typeof result !== 'undefined' ? true : false; }); } else { this.isOnFilter = false; } } }, { key: 'sort', value: function sort(order, sortField) { this.sortObj = { order: order, sortField: sortField }; var currentDisplayData = this.getCurrentDisplayData(); if (!this.colInfos[sortField]) return this; var sortFunc = this.colInfos[sortField].sortFunc; currentDisplayData = _sort(currentDisplayData, sortField, order, sortFunc); return this; } }, { key: 'page', value: function page(_page, sizePerPage) { this.pageObj.end = _page * sizePerPage - 1; this.pageObj.start = this.pageObj.end - (sizePerPage - 1); return this; } }, { key: 'edit', value: function edit(newVal, rowIndex, fieldName) { var currentDisplayData = this.getCurrentDisplayData(); var rowKeyCache = undefined; if (!this.enablePagination) { currentDisplayData[rowIndex][fieldName] = newVal; rowKeyCache = currentDisplayData[rowIndex][this.keyField]; } else { currentDisplayData[this.pageObj.start + rowIndex][fieldName] = newVal; rowKeyCache = currentDisplayData[this.pageObj.start + rowIndex][this.keyField]; } if (this.isOnFilter) { this.data.forEach(function (row) { if (row[this.keyField] === rowKeyCache) { row[fieldName] = newVal; } }, this); if (this.filterObj !== null) this.filter(this.filterObj); if (this.searchText !== null) this.search(this.searchText); } return this; } }, { key: 'addAtBegin', value: function addAtBegin(newObj) { if (!newObj[this.keyField] || newObj[this.keyField].toString() === '') { throw this.keyField + ' can\'t be empty value.'; } var currentDisplayData = this.getCurrentDisplayData(); currentDisplayData.forEach(function (row) { if (row[this.keyField].toString() === newObj[this.keyField].toString()) { throw this.keyField + ' ' + newObj[this.keyField] + ' already exists'; } }, this); currentDisplayData.unshift(newObj); if (this.isOnFilter) { this.data.unshift(newObj); } } }, { key: 'add', value: function add(newObj) { if (!newObj[this.keyField] || newObj[this.keyField].toString() === '') { throw this.keyField + ' can\'t be empty value.'; } var currentDisplayData = this.getCurrentDisplayData(); currentDisplayData.forEach(function (row) { if (row[this.keyField].toString() === newObj[this.keyField].toString()) { throw this.keyField + ' ' + newObj[this.keyField] + ' already exists'; } }, this); currentDisplayData.push(newObj); if (this.isOnFilter) { this.data.push(newObj); } } }, { key: 'remove', value: function remove(rowKey) { var _this2 = this; var currentDisplayData = this.getCurrentDisplayData(); var result = currentDisplayData.filter(function (row) { return rowKey.indexOf(row[_this2.keyField]) === -1; }); if (this.isOnFilter) { this.data = this.data.filter(function (row) { return rowKey.indexOf(row[_this2.keyField]) === -1; }); this.filteredData = result; } else { this.data = result; } } }, { key: 'filter', value: function filter(filterObj) { var _this3 = this; if (Object.keys(filterObj).length === 0) { this.filteredData = null; this.isOnFilter = false; this.filterObj = null; if (this.searchText !== null) this.search(this.searchText); } else { this.filterObj = filterObj; this.filteredData = this.data.filter(function (row) { var valid = true; var filterVal = undefined; for (var key in filterObj) { var targetVal = row[key]; switch (filterObj[key].type) { case _Const2['default'].FILTER_TYPE.NUMBER: { filterVal = filterObj[key].value.number; break; } case _Const2['default'].FILTER_TYPE.CUSTOM: { filterVal = typeof filterObj[key].value === 'object' ? undefined : typeof filterObj[key].value === 'string' ? filterObj[key].value.toLowerCase() : filterObj[key].value; break; } case _Const2['default'].FILTER_TYPE.REGEX: { filterVal = filterObj[key].value; break; } default: { filterVal = typeof filterObj[key].value === 'string' ? filterObj[key].value.toLowerCase() : filterObj[key].value; if (filterVal === undefined) { // Support old filter filterVal = filterObj[key].toLowerCase(); } break; } } if (_this3.colInfos[key]) { var _colInfos$key = _this3.colInfos[key]; var format = _colInfos$key.format; var filterFormatted = _colInfos$key.filterFormatted; var formatExtraData = _colInfos$key.formatExtraData; if (filterFormatted && format) { targetVal = format(row[key], row, formatExtraData); } } switch (filterObj[key].type) { case _Const2['default'].FILTER_TYPE.NUMBER: { valid = _this3.filterNumber(targetVal, filterVal, filterObj[key].value.comparator); break; } case _Const2['default'].FILTER_TYPE.DATE: { valid = _this3.filterDate(targetVal, filterVal); break; } case _Const2['default'].FILTER_TYPE.REGEX: { valid = _this3.filterRegex(targetVal, filterVal); break; } case _Const2['default'].FILTER_TYPE.CUSTOM: { valid = _this3.filterCustom(targetVal, filterVal, filterObj[key].value); break; } default: { valid = _this3.filterText(targetVal, filterVal); break; } } if (!valid) { break; } } return valid; }); this.isOnFilter = true; } } }, { key: 'filterNumber', value: function filterNumber(targetVal, filterVal, comparator) { var valid = true; switch (comparator) { case '=': { if (targetVal != filterVal) { valid = false; } break; } case '>': { if (targetVal <= filterVal) { valid = false; } break; } case '>=': { if (targetVal < filterVal) { valid = false; } break; } case '<': { if (targetVal >= filterVal) { valid = false; } break; } case '<=': { if (targetVal > filterVal) { valid = false; } break; } case '!=': { if (targetVal == filterVal) { valid = false; } break; } default: { console.error('Number comparator provided is not supported'); break; } } return valid; } }, { key: 'filterDate', value: function filterDate(targetVal, filterVal) { return targetVal.getDate() === filterVal.getDate() && targetVal.getMonth() === filterVal.getMonth() && targetVal.getFullYear() === filterVal.getFullYear(); } }, { key: 'filterRegex', value: function filterRegex(targetVal, filterVal) { try { return new RegExp(filterVal, 'i').test(targetVal); } catch (e) { console.error('Invalid regular expression'); return true; } } }, { key: 'filterCustom', value: function filterCustom(targetVal, filterVal, callbackInfo) { if (callbackInfo !== null && typeof callbackInfo === 'object') { return callbackInfo.callback(targetVal, callbackInfo.callbackParameters); } return this.filterText(targetVal, filterVal); } }, { key: 'filterText', value: function filterText(targetVal, filterVal) { if (targetVal.toString().toLowerCase().indexOf(filterVal) === -1) { return false; } return true; } /* General search function * It will search for the text if the input includes that text; */ }, { key: 'search', value: function search(searchText) { var _this4 = this; if (searchText.trim() === '') { this.filteredData = null; this.isOnFilter = false; this.searchText = null; if (this.filterObj !== null) this.filter(this.filterObj); } else { (function () { _this4.searchText = searchText; var searchTextArray = []; if (_this4.multiColumnSearch) { searchTextArray = searchText.split(' '); } else { searchTextArray.push(searchText); } var source = _this4.isOnFilter ? _this4.filteredData : _this4.data; _this4.filteredData = source.filter(function (row) { var keys = Object.keys(row); var valid = false; // for loops are ugly, but performance matters here. // And you cant break from a forEach. // http://jsperf.com/for-vs-foreach/66 for (var i = 0, keysLength = keys.length; i < keysLength; i++) { var key = keys[i]; if (_this4.colInfos[key] && row[key]) { var _colInfos$key2 = _this4.colInfos[key]; var format = _colInfos$key2.format; var filterFormatted = _colInfos$key2.filterFormatted; var formatExtraData = _colInfos$key2.formatExtraData; var searchable = _colInfos$key2.searchable; var targetVal = row[key]; if (searchable) { if (filterFormatted && format) { targetVal = format(targetVal, row, formatExtraData); } for (var j = 0, textLength = searchTextArray.length; j < textLength; j++) { var filterVal = searchTextArray[j].toLowerCase(); if (targetVal.toString().toLowerCase().indexOf(filterVal) !== -1) { valid = true; break; } } } } } return valid; }); _this4.isOnFilter = true; })(); } } }, { key: 'getDataIgnoringPagination', value: function getDataIgnoringPagination() { return this.getCurrentDisplayData(); } }, { key: 'get', value: function get() { var _data = this.getCurrentDisplayData(); if (_data.length === 0) return _data; if (this.remote || !this.enablePagination) { return _data; } else { var result = []; for (var i = this.pageObj.start; i <= this.pageObj.end; i++) { result.push(_data[i]); if (i + 1 === _data.length) break; } return result; } } }, { key: 'getKeyField', value: function getKeyField() { return this.keyField; } }, { key: 'getDataNum', value: function getDataNum() { return this.getCurrentDisplayData().length; } }, { key: 'isChangedPage', value: function isChangedPage() { return this.pageObj.start && this.pageObj.end ? true : false; } }, { key: 'getAllRowkey', value: function getAllRowkey() { var _this5 = this; return this.data.map(function (row) { return row[_this5.keyField]; }); } }]); return TableDataStore; })(); exports.TableDataStore = TableDataStore; /***/ }, /* 34 */ /***/ 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 } throw TypeError('Uncaught, unspecified "error" event.'); } } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: 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; } /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var _classnames = __webpack_require__(6); var _classnames2 = _interopRequireDefault(_classnames); exports['default'] = { renderReactSortCaret: function renderReactSortCaret(order) { var orderClass = (0, _classnames2['default'])('order', { 'dropup': order === _Const2['default'].SORT_ASC }); return _react2['default'].createElement( 'span', { className: orderClass }, _react2['default'].createElement('span', { className: 'caret', style: { margin: '0px 5px' } }) ); }, getScrollBarWidth: function getScrollBarWidth() { 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.appendChild(outer); var w1 = inner.offsetWidth; outer.style.overflow = 'scroll'; var w2 = inner.offsetWidth; if (w1 === w2) w2 = outer.clientWidth; document.body.removeChild(outer); return w1 - w2; }, canUseDOM: function canUseDOM() { return typeof window !== 'undefined' && typeof window.document !== 'undefined'; } }; module.exports = exports['default']; /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { /* eslint block-scoped-var: 0 */ /* eslint vars-on-top: 0 */ /* eslint no-var: 0 */ /* eslint no-unused-vars: 0 */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); if (typeof window !== 'undefined') { var filesaver = __webpack_require__(37); var saveAs = filesaver.saveAs; } function toString(data, keys) { var dataString = ''; if (data.length === 0) return dataString; dataString += keys.join(',') + '\n'; data.map(function (row) { keys.map(function (col, i) { var cell = typeof row[col] !== 'undefined' ? '"' + row[col] + '"' : ''; dataString += cell; if (i + 1 < keys.length) dataString += ','; }); dataString += '\n'; }); return dataString; } var exportCSV = function exportCSV(data, keys, filename) { var dataString = toString(data, keys); if (typeof window !== 'undefined') { saveAs(new Blob([dataString], { type: 'text/plain;charset=utf-8' }), filename || 'spreadsheet.csv'); } }; exports['default'] = exportCSV; module.exports = exports['default']; /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* FileSaver.js * A saveAs() FileSaver implementation. * 1.1.20151003 * * By Eli Grey, http://eligrey.com * License: MIT * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md */ /*global self */ /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */ /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */ "use strict"; var saveAs = saveAs || (function (view) { "use strict"; // IE <10 is explicitly unsupported if (typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) { return; } var doc = view.document, // only get URL when necessary in case Blob.js hasn't overridden it yet get_URL = function get_URL() { return view.URL || view.webkitURL || view; }, save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a"), can_use_save_link = ("download" in save_link), click = function click(node) { var event = new MouseEvent("click"); node.dispatchEvent(event); }, is_safari = /Version\/[\d\.]+.*Safari/.test(navigator.userAgent), webkit_req_fs = view.webkitRequestFileSystem, req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem, throw_outside = function throw_outside(ex) { (view.setImmediate || view.setTimeout)(function () { throw ex; }, 0); }, force_saveable_type = "application/octet-stream", fs_min_size = 0, // See https://code.google.com/p/chromium/issues/detail?id=375297#c7 and // https://github.com/eligrey/FileSaver.js/commit/485930a#commitcomment-8768047 // for the reasoning behind the timeout and revocation flow arbitrary_revoke_timeout = 500, // in ms revoke = function revoke(file) { var revoker = function revoker() { if (typeof file === "string") { // file is an object URL get_URL().revokeObjectURL(file); } else { // file is a File file.remove(); } }; if (view.chrome) { revoker(); } else { setTimeout(revoker, arbitrary_revoke_timeout); } }, dispatch = function dispatch(filesaver, event_types, event) { event_types = [].concat(event_types); var i = event_types.length; while (i--) { var listener = filesaver["on" + event_types[i]]; if (typeof listener === "function") { try { listener.call(filesaver, event || filesaver); } catch (ex) { throw_outside(ex); } } } }, auto_bom = function auto_bom(blob) { // prepend BOM for UTF-8 XML and text/* types (including HTML) if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) { return new Blob(["", blob], { type: blob.type }); } return blob; }, FileSaver = function FileSaver(blob, name, no_auto_bom) { if (!no_auto_bom) { blob = auto_bom(blob); } // First try a.download, then web filesystem, then object URLs var filesaver = this, type = blob.type, blob_changed = false, object_url, target_view, dispatch_all = function dispatch_all() { dispatch(filesaver, "writestart progress write writeend".split(" ")); }, // on any filesys errors revert to saving with object URLs fs_error = function fs_error() { if (target_view && is_safari && typeof FileReader !== "undefined") { // Safari doesn't allow downloading of blob urls var reader = new FileReader(); reader.onloadend = function () { var base64Data = reader.result; target_view.location.href = "data:attachment/file" + base64Data.slice(base64Data.search(/[,;]/)); filesaver.readyState = filesaver.DONE; dispatch_all(); }; reader.readAsDataURL(blob); filesaver.readyState = filesaver.INIT; return; } // don't create more object URLs than needed if (blob_changed || !object_url) { object_url = get_URL().createObjectURL(blob); } if (target_view) { target_view.location.href = object_url; } else { var new_tab = view.open(object_url, "_blank"); if (new_tab == undefined && is_safari) { //Apple do not allow window.open, see http://bit.ly/1kZffRI view.location.href = object_url; } } filesaver.readyState = filesaver.DONE; dispatch_all(); revoke(object_url); }, abortable = function abortable(func) { return function () { if (filesaver.readyState !== filesaver.DONE) { return func.apply(this, arguments); } }; }, create_if_not_found = { create: true, exclusive: false }, slice; filesaver.readyState = filesaver.INIT; if (!name) { name = "download"; } if (can_use_save_link) { object_url = get_URL().createObjectURL(blob); save_link.href = object_url; save_link.download = name; setTimeout(function () { click(save_link); dispatch_all(); revoke(object_url); filesaver.readyState = filesaver.DONE; }); return; } // Object and web filesystem URLs have a problem saving in Google Chrome when // viewed in a tab, so I force save with application/octet-stream // http://code.google.com/p/chromium/issues/detail?id=91158 // Update: Google errantly closed 91158, I submitted it again: // https://code.google.com/p/chromium/issues/detail?id=389642 if (view.chrome && type && type !== force_saveable_type) { slice = blob.slice || blob.webkitSlice; blob = slice.call(blob, 0, blob.size, force_saveable_type); blob_changed = true; } // Since I can't be sure that the guessed media type will trigger a download // in WebKit, I append .download to the filename. // https://bugs.webkit.org/show_bug.cgi?id=65440 if (webkit_req_fs && name !== "download") { name += ".download"; } if (type === force_saveable_type || webkit_req_fs) { target_view = view; } if (!req_fs) { fs_error(); return; } fs_min_size += blob.size; req_fs(view.TEMPORARY, fs_min_size, abortable(function (fs) { fs.root.getDirectory("saved", create_if_not_found, abortable(function (dir) { var save = function save() { dir.getFile(name, create_if_not_found, abortable(function (file) { file.createWriter(abortable(function (writer) { writer.onwriteend = function (event) { target_view.location.href = file.toURL(); filesaver.readyState = filesaver.DONE; dispatch(filesaver, "writeend", event); revoke(file); }; writer.onerror = function () { var error = writer.error; if (error.code !== error.ABORT_ERR) { fs_error(); } }; "writestart progress write abort".split(" ").forEach(function (event) { writer["on" + event] = filesaver["on" + event]; }); writer.write(blob); filesaver.abort = function () { writer.abort(); filesaver.readyState = filesaver.DONE; }; filesaver.readyState = filesaver.WRITING; }), fs_error); }), fs_error); }; dir.getFile(name, { create: false }, abortable(function (file) { // delete file if it already exists file.remove(); save(); }), abortable(function (ex) { if (ex.code === ex.NOT_FOUND_ERR) { save(); } else { fs_error(); } })); }), fs_error); }), fs_error); }, FS_proto = FileSaver.prototype, saveAs = function saveAs(blob, name, no_auto_bom) { return new FileSaver(blob, name, no_auto_bom); }; // IE 10+ (native saveAs) if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) { return function (blob, name, no_auto_bom) { if (!no_auto_bom) { blob = auto_bom(blob); } return navigator.msSaveOrOpenBlob(blob, name || "download"); }; } FS_proto.abort = function () { var filesaver = this; filesaver.readyState = filesaver.DONE; dispatch(filesaver, "abort"); }; FS_proto.readyState = FS_proto.INIT = 0; FS_proto.WRITING = 1; FS_proto.DONE = 2; FS_proto.error = FS_proto.onwritestart = FS_proto.onprogress = FS_proto.onwrite = FS_proto.onabort = FS_proto.onerror = FS_proto.onwriteend = null; return saveAs; })(typeof self !== "undefined" && self || typeof window !== "undefined" && window || undefined.content); // `self` is undefined in Firefox for Android content script context // while `this` is nsIContentFrameMessageManager // with an attribute `content` that corresponds to the window if (typeof module !== "undefined" && module.exports) { module.exports.saveAs = saveAs; } else if ("function" !== "undefined" && __webpack_require__(38) !== null && __webpack_require__(39) != null) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () { return saveAs; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } /***/ }, /* 38 */ /***/ function(module, exports) { module.exports = function() { throw new Error("define cannot be used indirect"); }; /***/ }, /* 39 */ /***/ function(module, exports) { /* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {module.exports = __webpack_amd_options__; /* WEBPACK VAR INJECTION */}.call(exports, {})) /***/ }, /* 40 */ /***/ 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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var _events = __webpack_require__(34); var Filter = (function (_EventEmitter) { _inherits(Filter, _EventEmitter); function Filter(data) { _classCallCheck(this, Filter); _get(Object.getPrototypeOf(Filter.prototype), 'constructor', this).call(this, data); this.currentFilter = {}; } _createClass(Filter, [{ key: 'handleFilter', value: function handleFilter(dataField, value, type) { var filterType = type || _Const2['default'].FILTER_TYPE.CUSTOM; if (value !== null && typeof value === 'object') { // value of the filter is an object var hasValue = true; for (var prop in value) { if (!value[prop] || value[prop] === '') { hasValue = false; break; } } // if one of the object properties is undefined or empty, we remove the filter if (hasValue) { this.currentFilter[dataField] = { value: value, type: filterType }; } else { delete this.currentFilter[dataField]; } } else if (!value || value.trim() === '') { delete this.currentFilter[dataField]; } else { this.currentFilter[dataField] = { value: value.trim(), type: filterType }; } this.emit('onFilterChange', this.currentFilter); } }]); return Filter; })(_events.EventEmitter); exports.Filter = Filter; /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { /* eslint default-case: 0 */ /* eslint guard-for-in: 0 */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var _util = __webpack_require__(35); var _util2 = _interopRequireDefault(_util); var _filtersDate = __webpack_require__(42); var _filtersDate2 = _interopRequireDefault(_filtersDate); var _filtersText = __webpack_require__(43); var _filtersText2 = _interopRequireDefault(_filtersText); var _filtersRegex = __webpack_require__(44); var _filtersRegex2 = _interopRequireDefault(_filtersRegex); var _filtersSelect = __webpack_require__(45); var _filtersSelect2 = _interopRequireDefault(_filtersSelect); var _filtersNumber = __webpack_require__(46); var _filtersNumber2 = _interopRequireDefault(_filtersNumber); var TableHeaderColumn = (function (_Component) { _inherits(TableHeaderColumn, _Component); function TableHeaderColumn(props) { var _this = this; _classCallCheck(this, TableHeaderColumn); _get(Object.getPrototypeOf(TableHeaderColumn.prototype), 'constructor', this).call(this, props); this.handleColumnClick = function () { if (!_this.props.dataSort) return; var order = _this.props.sort === _Const2['default'].SORT_DESC ? _Const2['default'].SORT_ASC : _Const2['default'].SORT_DESC; _this.props.onSort(order, _this.props.dataField); }; this.handleFilter = this.handleFilter.bind(this); } _createClass(TableHeaderColumn, [{ key: 'handleFilter', value: function handleFilter(value, type) { this.props.filter.emitter.handleFilter(this.props.dataField, value, type); } }, { key: 'getFilters', value: function getFilters() { switch (this.props.filter.type) { case _Const2['default'].FILTER_TYPE.TEXT: { return _react2['default'].createElement(_filtersText2['default'], _extends({}, this.props.filter, { columnName: this.props.children, filterHandler: this.handleFilter })); } case _Const2['default'].FILTER_TYPE.REGEX: { return _react2['default'].createElement(_filtersRegex2['default'], _extends({}, this.props.filter, { columnName: this.props.children, filterHandler: this.handleFilter })); } case _Const2['default'].FILTER_TYPE.SELECT: { return _react2['default'].createElement(_filtersSelect2['default'], _extends({}, this.props.filter, { columnName: this.props.children, filterHandler: this.handleFilter })); } case _Const2['default'].FILTER_TYPE.NUMBER: { return _react2['default'].createElement(_filtersNumber2['default'], _extends({}, this.props.filter, { columnName: this.props.children, filterHandler: this.handleFilter })); } case _Const2['default'].FILTER_TYPE.DATE: { return _react2['default'].createElement(_filtersDate2['default'], _extends({}, this.props.filter, { columnName: this.props.children, filterHandler: this.handleFilter })); } case _Const2['default'].FILTER_TYPE.CUSTOM: { return this.props.filter.getElement(this.handleFilter, this.props.filter.customFilterParameters); } } } }, { key: 'componentDidMount', value: function componentDidMount() { this.refs['header-col'].setAttribute('data-field', this.props.dataField); } }, { key: 'render', value: function render() { var defaultCaret = undefined; var thStyle = { textAlign: this.props.dataAlign, display: this.props.hidden ? 'none' : null }; if (this.props.sortIndicator) { defaultCaret = !this.props.dataSort ? null : _react2['default'].createElement( 'span', { className: 'order' }, _react2['default'].createElement( 'span', { className: 'dropdown' }, _react2['default'].createElement('span', { className: 'caret', style: { margin: '10px 0 10px 5px', color: '#ccc' } }) ), _react2['default'].createElement( 'span', { className: 'dropup' }, _react2['default'].createElement('span', { className: 'caret', style: { margin: '10px 0', color: '#ccc' } }) ) ); } var sortCaret = this.props.sort ? _util2['default'].renderReactSortCaret(this.props.sort) : defaultCaret; var classes = this.props.className + ' ' + (this.props.dataSort ? 'sort-column' : ''); return _react2['default'].createElement( 'th', { ref: 'header-col', className: classes, style: thStyle, title: this.props.children, onClick: this.handleColumnClick }, this.props.children, sortCaret, _react2['default'].createElement( 'div', { onClick: function (e) { return e.stopPropagation(); } }, this.props.filter ? this.getFilters() : null ) ); } }]); return TableHeaderColumn; })(_react.Component); var filterTypeArray = []; for (var key in _Const2['default'].FILTER_TYPE) { filterTypeArray.push(_Const2['default'].FILTER_TYPE[key]); } TableHeaderColumn.propTypes = { dataField: _react.PropTypes.string, dataAlign: _react.PropTypes.string, dataSort: _react.PropTypes.bool, onSort: _react.PropTypes.func, dataFormat: _react.PropTypes.func, isKey: _react.PropTypes.bool, editable: _react.PropTypes.any, hidden: _react.PropTypes.bool, searchable: _react.PropTypes.bool, className: _react.PropTypes.string, width: _react.PropTypes.string, sortFunc: _react.PropTypes.func, columnClassName: _react.PropTypes.any, filterFormatted: _react.PropTypes.bool, sort: _react.PropTypes.string, formatExtraData: _react.PropTypes.any, filter: _react.PropTypes.shape({ type: _react.PropTypes.oneOf(filterTypeArray), delay: _react.PropTypes.number, options: _react.PropTypes.oneOfType([_react.PropTypes.object, // for SelectFilter _react.PropTypes.arrayOf(_react.PropTypes.number) // for NumberFilter ]), numberComparators: _react.PropTypes.arrayOf(_react.PropTypes.string), emitter: _react.PropTypes.object, placeholder: _react.PropTypes.string, getElement: _react.PropTypes.func, customFilterParameters: _react.PropTypes.object }), sortIndicator: _react.PropTypes.bool }; TableHeaderColumn.defaultProps = { dataAlign: 'left', dataSort: false, dataFormat: undefined, isKey: false, editable: true, onSort: undefined, hidden: false, searchable: true, className: '', width: null, sortFunc: undefined, columnClassName: '', filterFormatted: false, sort: undefined, formatExtraData: undefined, filter: undefined, sortIndicator: true }; exports['default'] = TableHeaderColumn; module.exports = exports['default']; /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { /* eslint quotes: 0 */ /* eslint max-len: 0 */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var DateFilter = (function (_Component) { _inherits(DateFilter, _Component); function DateFilter(props) { _classCallCheck(this, DateFilter); _get(Object.getPrototypeOf(DateFilter.prototype), 'constructor', this).call(this, props); this.filter = this.filter.bind(this); } _createClass(DateFilter, [{ key: 'setDefaultDate', value: function setDefaultDate() { var defaultDate = ''; if (this.props.defaultValue) { // Set the appropriate format for the input type=date, i.e. "YYYY-MM-DD" var defaultValue = new Date(this.props.defaultValue); defaultDate = defaultValue.getFullYear() + '-' + ("0" + (defaultValue.getMonth() + 1)).slice(-2) + '-' + ("0" + defaultValue.getDate()).slice(-2); } return defaultDate; } }, { key: 'filter', value: function filter(event) { var dateValue = event.target.value; if (dateValue) { this.props.filterHandler(new Date(dateValue), _Const2['default'].FILTER_TYPE.DATE); } else { this.props.filterHandler(null, _Const2['default'].FILTER_TYPE.DATE); } } }, { key: 'componentDidMount', value: function componentDidMount() { var dateValue = this.refs.inputDate.defaultValue; if (dateValue) { this.props.filterHandler(new Date(dateValue), _Const2['default'].FILTER_TYPE.DATE); } } }, { key: 'render', value: function render() { return _react2['default'].createElement('input', { ref: 'inputDate', className: 'filter date-filter form-control', type: 'date', onChange: this.filter, defaultValue: this.setDefaultDate() }); } }]); return DateFilter; })(_react.Component); DateFilter.propTypes = { filterHandler: _react.PropTypes.func.isRequired, defaultValue: _react.PropTypes.object, columnName: _react.PropTypes.string }; exports['default'] = DateFilter; module.exports = exports['default']; /***/ }, /* 43 */ /***/ 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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var TextFilter = (function (_Component) { _inherits(TextFilter, _Component); function TextFilter(props) { _classCallCheck(this, TextFilter); _get(Object.getPrototypeOf(TextFilter.prototype), 'constructor', this).call(this, props); this.filter = this.filter.bind(this); this.timeout = null; } _createClass(TextFilter, [{ key: 'filter', value: function filter(event) { var _this = this; if (this.timeout) { clearTimeout(this.timeout); } var filterValue = event.target.value; this.timeout = setTimeout(function () { _this.props.filterHandler(filterValue, _Const2['default'].FILTER_TYPE.TEXT); }, this.props.delay); } }, { key: 'componentDidMount', value: function componentDidMount() { var defaultValue = this.refs.inputText.defaultValue; if (defaultValue) { this.props.filterHandler(defaultValue, _Const2['default'].FILTER_TYPE.TEXT); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { clearTimeout(this.timeout); } }, { key: 'render', value: function render() { var _props = this.props; var placeholder = _props.placeholder; var columnName = _props.columnName; var defaultValue = _props.defaultValue; return _react2['default'].createElement('input', { ref: 'inputText', className: 'filter text-filter form-control', type: 'text', onChange: this.filter, placeholder: placeholder || 'Enter ' + columnName + '...', defaultValue: defaultValue ? defaultValue : '' }); } }]); return TextFilter; })(_react.Component); TextFilter.propTypes = { filterHandler: _react.PropTypes.func.isRequired, defaultValue: _react.PropTypes.string, delay: _react.PropTypes.number, placeholder: _react.PropTypes.string, columnName: _react.PropTypes.string }; TextFilter.defaultProps = { delay: _Const2['default'].FILTER_DELAY }; exports['default'] = TextFilter; module.exports = exports['default']; /***/ }, /* 44 */ /***/ 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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var RegexFilter = (function (_Component) { _inherits(RegexFilter, _Component); function RegexFilter(props) { _classCallCheck(this, RegexFilter); _get(Object.getPrototypeOf(RegexFilter.prototype), 'constructor', this).call(this, props); this.filter = this.filter.bind(this); this.timeout = null; } _createClass(RegexFilter, [{ key: 'filter', value: function filter(event) { var _this = this; if (this.timeout) { clearTimeout(this.timeout); } var filterValue = event.target.value; this.timeout = setTimeout(function () { _this.props.filterHandler(filterValue, _Const2['default'].FILTER_TYPE.REGEX); }, this.props.delay); } }, { key: 'componentDidMount', value: function componentDidMount() { var value = this.refs.inputText.defaultValue; if (value) { this.props.filterHandler(value, _Const2['default'].FILTER_TYPE.REGEX); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { clearTimeout(this.timeout); } }, { key: 'render', value: function render() { var _props = this.props; var defaultValue = _props.defaultValue; var placeholder = _props.placeholder; var columnName = _props.columnName; return _react2['default'].createElement('input', { ref: 'inputText', className: 'filter text-filter form-control', type: 'text', onChange: this.filter, placeholder: placeholder || 'Enter Regex for ' + columnName + '...', defaultValue: defaultValue ? defaultValue : '' }); } }]); return RegexFilter; })(_react.Component); RegexFilter.propTypes = { filterHandler: _react.PropTypes.func.isRequired, defaultValue: _react.PropTypes.string, delay: _react.PropTypes.number, placeholder: _react.PropTypes.string, columnName: _react.PropTypes.string }; RegexFilter.defaultProps = { delay: _Const2['default'].FILTER_DELAY }; exports['default'] = RegexFilter; module.exports = exports['default']; /***/ }, /* 45 */ /***/ 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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(6); var _classnames2 = _interopRequireDefault(_classnames); var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var SelectFilter = (function (_Component) { _inherits(SelectFilter, _Component); function SelectFilter(props) { _classCallCheck(this, SelectFilter); _get(Object.getPrototypeOf(SelectFilter.prototype), 'constructor', this).call(this, props); this.filter = this.filter.bind(this); this.state = { isPlaceholderSelected: this.props.defaultValue === undefined || !this.props.options.hasOwnProperty(this.props.defaultValue) }; } _createClass(SelectFilter, [{ key: 'filter', value: function filter(event) { var value = event.target.value; this.setState({ isPlaceholderSelected: value === '' }); this.props.filterHandler(value, _Const2['default'].FILTER_TYPE.SELECT); } }, { key: 'getOptions', value: function getOptions() { var optionTags = []; var _props = this.props; var options = _props.options; var placeholder = _props.placeholder; var columnName = _props.columnName; optionTags.push(_react2['default'].createElement( 'option', { key: '-1', value: '' }, placeholder || 'Select ' + columnName + '...' )); Object.keys(options).map(function (key) { optionTags.push(_react2['default'].createElement( 'option', { key: key, value: key }, options[key] )); }); return optionTags; } }, { key: 'componentDidMount', value: function componentDidMount() { var value = this.refs.selectInput.value; if (value) { this.props.filterHandler(value, _Const2['default'].FILTER_TYPE.SELECT); } } }, { key: 'render', value: function render() { var selectClass = (0, _classnames2['default'])('filter', 'select-filter', 'form-control', { 'placeholder-selected': this.state.isPlaceholderSelected }); return _react2['default'].createElement( 'select', { ref: 'selectInput', className: selectClass, onChange: this.filter, defaultValue: this.props.defaultValue !== undefined ? this.props.defaultValue : '' }, this.getOptions() ); } }]); return SelectFilter; })(_react.Component); SelectFilter.propTypes = { filterHandler: _react.PropTypes.func.isRequired, options: _react.PropTypes.object.isRequired, placeholder: _react.PropTypes.string, columnName: _react.PropTypes.string }; exports['default'] = SelectFilter; module.exports = exports['default']; /***/ }, /* 46 */ /***/ 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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(6); var _classnames2 = _interopRequireDefault(_classnames); var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var legalComparators = ['=', '>', '>=', '<', '<=', '!=']; var NumberFilter = (function (_Component) { _inherits(NumberFilter, _Component); function NumberFilter(props) { _classCallCheck(this, NumberFilter); _get(Object.getPrototypeOf(NumberFilter.prototype), 'constructor', this).call(this, props); this.numberComparators = this.props.numberComparators || legalComparators; this.timeout = null; this.state = { isPlaceholderSelected: this.props.defaultValue === undefined || this.props.defaultValue.number === undefined || this.props.options && this.props.options.indexOf(this.props.defaultValue.number) === -1 }; this.onChangeNumber = this.onChangeNumber.bind(this); this.onChangeNumberSet = this.onChangeNumberSet.bind(this); this.onChangeComparator = this.onChangeComparator.bind(this); } _createClass(NumberFilter, [{ key: 'onChangeNumber', value: function onChangeNumber(event) { var _this = this; var comparator = this.refs.numberFilterComparator.value; if (comparator === '') { return; } if (this.timeout) { clearTimeout(this.timeout); } var filterValue = event.target.value; this.timeout = setTimeout(function () { _this.props.filterHandler({ number: filterValue, comparator: comparator }, _Const2['default'].FILTER_TYPE.NUMBER); }, this.props.delay); } }, { key: 'onChangeNumberSet', value: function onChangeNumberSet(event) { var comparator = this.refs.numberFilterComparator.value; var value = event.target.value; this.setState({ isPlaceholderSelected: value === '' }); if (comparator === '') { return; } this.props.filterHandler({ number: value, comparator: comparator }, _Const2['default'].FILTER_TYPE.NUMBER); } }, { key: 'onChangeComparator', value: function onChangeComparator(event) { var value = this.refs.numberFilter.value; var comparator = event.target.value; if (value === '') { return; } this.props.filterHandler({ number: value, comparator: comparator }, _Const2['default'].FILTER_TYPE.NUMBER); } }, { key: 'getComparatorOptions', value: function getComparatorOptions() { var optionTags = []; optionTags.push(_react2['default'].createElement('option', { key: '-1' })); for (var i = 0; i < this.numberComparators.length; i++) { optionTags.push(_react2['default'].createElement( 'option', { key: i, value: this.numberComparators[i] }, this.numberComparators[i] )); } return optionTags; } }, { key: 'getNumberOptions', value: function getNumberOptions() { var optionTags = []; var options = this.props.options; optionTags.push(_react2['default'].createElement( 'option', { key: '-1', value: '' }, this.props.placeholder || 'Select ' + this.props.columnName + '...' )); for (var i = 0; i < options.length; i++) { optionTags.push(_react2['default'].createElement( 'option', { key: i, value: options[i] }, options[i] )); } return optionTags; } }, { key: 'componentDidMount', value: function componentDidMount() { var comparator = this.refs.numberFilterComparator.value; var number = this.refs.numberFilter.value; if (comparator && number) { this.props.filterHandler({ number: number, comparator: comparator }, _Const2['default'].FILTER_TYPE.NUMBER); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { clearTimeout(this.timeout); } }, { key: 'render', value: function render() { var selectClass = (0, _classnames2['default'])('select-filter', 'number-filter-input', 'form-control', { 'placeholder-selected': this.state.isPlaceholderSelected }); return _react2['default'].createElement( 'div', { className: 'filter number-filter' }, _react2['default'].createElement( 'select', { ref: 'numberFilterComparator', className: 'number-filter-comparator form-control', onChange: this.onChangeComparator, defaultValue: this.props.defaultValue ? this.props.defaultValue.comparator : '' }, this.getComparatorOptions() ), this.props.options ? _react2['default'].createElement( 'select', { ref: 'numberFilter', className: selectClass, onChange: this.onChangeNumberSet, defaultValue: this.props.defaultValue ? this.props.defaultValue.number : '' }, this.getNumberOptions() ) : _react2['default'].createElement('input', { ref: 'numberFilter', type: 'number', className: 'number-filter-input form-control', placeholder: this.props.placeholder || 'Enter ' + this.props.columnName + '...', onChange: this.onChangeNumber, defaultValue: this.props.defaultValue ? this.props.defaultValue.number : '' }) ); } }]); return NumberFilter; })(_react.Component); NumberFilter.propTypes = { filterHandler: _react.PropTypes.func.isRequired, options: _react.PropTypes.arrayOf(_react.PropTypes.number), defaultValue: _react.PropTypes.shape({ number: _react.PropTypes.number, comparator: _react.PropTypes.oneOf(legalComparators) }), delay: _react.PropTypes.number, /* eslint consistent-return: 0 */ numberComparators: function numberComparators(props, propName) { if (!props[propName]) { return; } for (var i = 0; i < props[propName].length; i++) { var comparatorIsValid = false; for (var j = 0; j < legalComparators.length; j++) { if (legalComparators[j] === props[propName][i]) { comparatorIsValid = true; break; } } if (!comparatorIsValid) { return new Error('Number comparator provided is not supported.\n Use only ' + legalComparators); } } }, placeholder: _react.PropTypes.string, columnName: _react.PropTypes.string }; NumberFilter.defaultProps = { delay: _Const2['default'].FILTER_DELAY }; exports['default'] = NumberFilter; module.exports = exports['default']; /***/ } /******/ ]) }); ; //# sourceMappingURL=react-bootstrap-table.js.map
server/startup/registry/i18n.js
hrath2015/reaction
import { Reaction } from "/server/api"; export default function () { Reaction.registerPackage({ label: "i18n", name: "reaction-i18n", icon: "fa fa-language", autoEnable: true, settings: { name: "i18n" }, registry: [{ provides: "dashboard", template: "i18nDashboard", label: "i18n", description: "Internationalization utilities", icon: "fa fa-language", priority: 1, container: "utilities" }, { provides: "settings", template: "i18nSettings", label: "Localization and i18n", container: "reaction-i18n" }] }); }
ngiiedu-client/src/components/admin/school/sync/common/SampleCheckList.js
jinifor/branchtest
import React, { Component } from 'react'; import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn, } from 'material-ui/Table'; //redux //store에 연결 import { connect } from 'react-redux'; //action 객체사용 import * as actions from '../../../../../actions/index'; class SampleCheckList extends Component { render() { return ( <div > <Table headerStyle={{ width:3000, height:50 }} bodyStyle={{ width:3000, height:432 }} selectable={false} > <TableHeader displaySelectAll={false} adjustForCheckbox={false} > <TableRow> {this.props.apiColumn.map( (row, index) => ( <TableHeaderColumn key={index}>{row}</TableHeaderColumn> ))} </TableRow> </TableHeader> <TableBody displayRowCheckbox={false} > {this.props.tableData.map( (row, index) => ( <TableRow key={row.학교ID}> {this.props.apiColumn.map( (row2,index2 ) => ( <TableRowColumn key={index+'-'+index2}>{eval("row."+row2)}</TableRowColumn> ))} </TableRow> ))} </TableBody> </Table> </div> ); } } SampleCheckList.defaultProps = { apiColumn:[] }; export default SampleCheckList;
src/DropDown/index.js
Paratron/modoJS
import React from 'react'; import PropTypes from 'prop-types'; import Button from '../Button'; import List from '../List'; import Card from '../Card'; const propTypes = { items: PropTypes.oneOfType([PropTypes.object, PropTypes.array]).isRequired, value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), renderButtonLabel: PropTypes.func, onChange: PropTypes.func, className: PropTypes.string, enabled: PropTypes.bool }; const defaultProps = { renderButtonLabel: (value, items) => items[value], onChange: () => { }, enabled: true }; export const handleListClick = (onChange, setDropDownOpen) => (index) => { if (onChange) { onChange(index); } setDropDownOpen(false); }; export const handleButtonClick = (dropdownOpen, setDropdownOpen) => () => { setDropdownOpen(!dropdownOpen); }; const DropDown = (props) => { const [dropDownOpen, setDropDownOpen] = React.useState(false); const { items, value, onChange, className, renderButtonLabel, enabled } = props; const classNames = ['mdo-dropdown']; if (dropDownOpen) { classNames.push('mdo-open'); } if (!enabled) { classNames.push('mdo-disabled'); } if (className) { classNames.push(className); } return ( <div className={classNames.join(' ')}> <Button enabled={enabled} onClick={handleButtonClick(dropDownOpen, setDropDownOpen)} > {renderButtonLabel(value, items)} </Button> <i className="material-icons"> arrow_drop_down </i> <Card> <List items={items} onChange={handleListClick(onChange,setDropDownOpen)} /> </Card> </div> ); }; DropDown.propTypes = propTypes; DropDown.defaultProps = defaultProps; export default DropDown;
node_modules/jsdom/example/jquery/jquery.js
towski/disc-jockey
/*! * jQuery JavaScript Library v1.4.4 * http://jquery.com/ * * Copyright 2010, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2010, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Thu Nov 11 19:04:53 2010 -0500 */ (function(E,B){function ka(a,b,d){if(d===B&&a.nodeType===1){d=a.getAttribute("data-"+b);if(typeof d==="string"){try{d=d==="true"?true:d==="false"?false:d==="null"?null:!c.isNaN(d)?parseFloat(d):Ja.test(d)?c.parseJSON(d):d}catch(e){}c.data(a,b,d)}else d=B}return d}function U(){return false}function ca(){return true}function la(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function Ka(a){var b,d,e,f,h,l,k,o,x,r,A,C=[];f=[];h=c.data(this,this.nodeType?"events":"__events__");if(typeof h==="function")h= h.events;if(!(a.liveFired===this||!h||!h.live||a.button&&a.type==="click")){if(a.namespace)A=RegExp("(^|\\.)"+a.namespace.split(".").join("\\.(?:.*\\.)?")+"(\\.|$)");a.liveFired=this;var J=h.live.slice(0);for(k=0;k<J.length;k++){h=J[k];h.origType.replace(X,"")===a.type?f.push(h.selector):J.splice(k--,1)}f=c(a.target).closest(f,a.currentTarget);o=0;for(x=f.length;o<x;o++){r=f[o];for(k=0;k<J.length;k++){h=J[k];if(r.selector===h.selector&&(!A||A.test(h.namespace))){l=r.elem;e=null;if(h.preType==="mouseenter"|| h.preType==="mouseleave"){a.type=h.preType;e=c(a.relatedTarget).closest(h.selector)[0]}if(!e||e!==l)C.push({elem:l,handleObj:h,level:r.level})}}}o=0;for(x=C.length;o<x;o++){f=C[o];if(d&&f.level>d)break;a.currentTarget=f.elem;a.data=f.handleObj.data;a.handleObj=f.handleObj;A=f.handleObj.origHandler.apply(f.elem,arguments);if(A===false||a.isPropagationStopped()){d=f.level;if(A===false)b=false;if(a.isImmediatePropagationStopped())break}}return b}}function Y(a,b){return(a&&a!=="*"?a+".":"")+b.replace(La, "`").replace(Ma,"&")}function ma(a,b,d){if(c.isFunction(b))return c.grep(a,function(f,h){return!!b.call(f,h,f)===d});else if(b.nodeType)return c.grep(a,function(f){return f===b===d});else if(typeof b==="string"){var e=c.grep(a,function(f){return f.nodeType===1});if(Na.test(b))return c.filter(b,e,!d);else b=c.filter(b,e)}return c.grep(a,function(f){return c.inArray(f,b)>=0===d})}function na(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var e=c.data(a[d++]),f=c.data(this, e);if(e=e&&e.events){delete f.handle;f.events={};for(var h in e)for(var l in e[h])c.event.add(this,h,e[h][l],e[h][l].data)}}})}function Oa(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function oa(a,b,d){var e=b==="width"?a.offsetWidth:a.offsetHeight;if(d==="border")return e;c.each(b==="width"?Pa:Qa,function(){d||(e-=parseFloat(c.css(a,"padding"+this))||0);if(d==="margin")e+=parseFloat(c.css(a, "margin"+this))||0;else e-=parseFloat(c.css(a,"border"+this+"Width"))||0});return e}function da(a,b,d,e){if(c.isArray(b)&&b.length)c.each(b,function(f,h){d||Ra.test(a)?e(a,h):da(a+"["+(typeof h==="object"||c.isArray(h)?f:"")+"]",h,d,e)});else if(!d&&b!=null&&typeof b==="object")c.isEmptyObject(b)?e(a,""):c.each(b,function(f,h){da(a+"["+f+"]",h,d,e)});else e(a,b)}function S(a,b){var d={};c.each(pa.concat.apply([],pa.slice(0,b)),function(){d[this]=a});return d}function qa(a){if(!ea[a]){var b=c("<"+ a+">").appendTo("body"),d=b.css("display");b.remove();if(d==="none"||d==="")d="block";ea[a]=d}return ea[a]}function fa(a){return c.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var t=E.document,c=function(){function a(){if(!b.isReady){try{t.documentElement.doScroll("left")}catch(j){setTimeout(a,1);return}b.ready()}}var b=function(j,s){return new b.fn.init(j,s)},d=E.jQuery,e=E.$,f,h=/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,l=/\S/,k=/^\s+/,o=/\s+$/,x=/\W/,r=/\d/,A=/^<(\w+)\s*\/?>(?:<\/\1>)?$/, C=/^[\],:{}\s]*$/,J=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,w=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,I=/(?:^|:|,)(?:\s*\[)+/g,L=/(webkit)[ \/]([\w.]+)/,g=/(opera)(?:.*version)?[ \/]([\w.]+)/,i=/(msie) ([\w.]+)/,n=/(mozilla)(?:.*? rv:([\w.]+))?/,m=navigator.userAgent,p=false,q=[],u,y=Object.prototype.toString,F=Object.prototype.hasOwnProperty,M=Array.prototype.push,N=Array.prototype.slice,O=String.prototype.trim,D=Array.prototype.indexOf,R={};b.fn=b.prototype={init:function(j, s){var v,z,H;if(!j)return this;if(j.nodeType){this.context=this[0]=j;this.length=1;return this}if(j==="body"&&!s&&t.body){this.context=t;this[0]=t.body;this.selector="body";this.length=1;return this}if(typeof j==="string")if((v=h.exec(j))&&(v[1]||!s))if(v[1]){H=s?s.ownerDocument||s:t;if(z=A.exec(j))if(b.isPlainObject(s)){j=[t.createElement(z[1])];b.fn.attr.call(j,s,true)}else j=[H.createElement(z[1])];else{z=b.buildFragment([v[1]],[H]);j=(z.cacheable?z.fragment.cloneNode(true):z.fragment).childNodes}return b.merge(this, j)}else{if((z=t.getElementById(v[2]))&&z.parentNode){if(z.id!==v[2])return f.find(j);this.length=1;this[0]=z}this.context=t;this.selector=j;return this}else if(!s&&!x.test(j)){this.selector=j;this.context=t;j=t.getElementsByTagName(j);return b.merge(this,j)}else return!s||s.jquery?(s||f).find(j):b(s).find(j);else if(b.isFunction(j))return f.ready(j);if(j.selector!==B){this.selector=j.selector;this.context=j.context}return b.makeArray(j,this)},selector:"",jquery:"1.4.4",length:0,size:function(){return this.length}, toArray:function(){return N.call(this,0)},get:function(j){return j==null?this.toArray():j<0?this.slice(j)[0]:this[j]},pushStack:function(j,s,v){var z=b();b.isArray(j)?M.apply(z,j):b.merge(z,j);z.prevObject=this;z.context=this.context;if(s==="find")z.selector=this.selector+(this.selector?" ":"")+v;else if(s)z.selector=this.selector+"."+s+"("+v+")";return z},each:function(j,s){return b.each(this,j,s)},ready:function(j){b.bindReady();if(b.isReady)j.call(t,b);else q&&q.push(j);return this},eq:function(j){return j=== -1?this.slice(j):this.slice(j,+j+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(N.apply(this,arguments),"slice",N.call(arguments).join(","))},map:function(j){return this.pushStack(b.map(this,function(s,v){return j.call(s,v,s)}))},end:function(){return this.prevObject||b(null)},push:M,sort:[].sort,splice:[].splice};b.fn.init.prototype=b.fn;b.extend=b.fn.extend=function(){var j,s,v,z,H,G=arguments[0]||{},K=1,Q=arguments.length,ga=false; if(typeof G==="boolean"){ga=G;G=arguments[1]||{};K=2}if(typeof G!=="object"&&!b.isFunction(G))G={};if(Q===K){G=this;--K}for(;K<Q;K++)if((j=arguments[K])!=null)for(s in j){v=G[s];z=j[s];if(G!==z)if(ga&&z&&(b.isPlainObject(z)||(H=b.isArray(z)))){if(H){H=false;v=v&&b.isArray(v)?v:[]}else v=v&&b.isPlainObject(v)?v:{};G[s]=b.extend(ga,v,z)}else if(z!==B)G[s]=z}return G};b.extend({noConflict:function(j){E.$=e;if(j)E.jQuery=d;return b},isReady:false,readyWait:1,ready:function(j){j===true&&b.readyWait--; if(!b.readyWait||j!==true&&!b.isReady){if(!t.body)return setTimeout(b.ready,1);b.isReady=true;if(!(j!==true&&--b.readyWait>0))if(q){var s=0,v=q;for(q=null;j=v[s++];)j.call(t,b);b.fn.trigger&&b(t).trigger("ready").unbind("ready")}}},bindReady:function(){if(!p){p=true;if(t.readyState==="complete")return setTimeout(b.ready,1);if(t.addEventListener){t.addEventListener("DOMContentLoaded",u,false);E.addEventListener("load",b.ready,false)}else if(t.attachEvent){t.attachEvent("onreadystatechange",u);E.attachEvent("onload", b.ready);var j=false;try{j=E.frameElement==null}catch(s){}t.documentElement.doScroll&&j&&a()}}},isFunction:function(j){return b.type(j)==="function"},isArray:Array.isArray||function(j){return b.type(j)==="array"},isWindow:function(j){return j&&typeof j==="object"&&"setInterval"in j},isNaN:function(j){return j==null||!r.test(j)||isNaN(j)},type:function(j){return j==null?String(j):R[y.call(j)]||"object"},isPlainObject:function(j){if(!j||b.type(j)!=="object"||j.nodeType||b.isWindow(j))return false;if(j.constructor&& !F.call(j,"constructor")&&!F.call(j.constructor.prototype,"isPrototypeOf"))return false;for(var s in j);return s===B||F.call(j,s)},isEmptyObject:function(j){for(var s in j)return false;return true},error:function(j){throw j;},parseJSON:function(j){if(typeof j!=="string"||!j)return null;j=b.trim(j);if(C.test(j.replace(J,"@").replace(w,"]").replace(I,"")))return E.JSON&&E.JSON.parse?E.JSON.parse(j):(new Function("return "+j))();else b.error("Invalid JSON: "+j)},noop:function(){},globalEval:function(j){if(j&& l.test(j)){var s=t.getElementsByTagName("head")[0]||t.documentElement,v=t.createElement("script");v.type="text/javascript";if(b.support.scriptEval)v.appendChild(t.createTextNode(j));else v.text=j;s.insertBefore(v,s.firstChild);s.removeChild(v)}},nodeName:function(j,s){return j.nodeName&&j.nodeName.toUpperCase()===s.toUpperCase()},each:function(j,s,v){var z,H=0,G=j.length,K=G===B||b.isFunction(j);if(v)if(K)for(z in j){if(s.apply(j[z],v)===false)break}else for(;H<G;){if(s.apply(j[H++],v)===false)break}else if(K)for(z in j){if(s.call(j[z], z,j[z])===false)break}else for(v=j[0];H<G&&s.call(v,H,v)!==false;v=j[++H]);return j},trim:O?function(j){return j==null?"":O.call(j)}:function(j){return j==null?"":j.toString().replace(k,"").replace(o,"")},makeArray:function(j,s){var v=s||[];if(j!=null){var z=b.type(j);j.length==null||z==="string"||z==="function"||z==="regexp"||b.isWindow(j)?M.call(v,j):b.merge(v,j)}return v},inArray:function(j,s){if(s.indexOf)return s.indexOf(j);for(var v=0,z=s.length;v<z;v++)if(s[v]===j)return v;return-1},merge:function(j, s){var v=j.length,z=0;if(typeof s.length==="number")for(var H=s.length;z<H;z++)j[v++]=s[z];else for(;s[z]!==B;)j[v++]=s[z++];j.length=v;return j},grep:function(j,s,v){var z=[],H;v=!!v;for(var G=0,K=j.length;G<K;G++){H=!!s(j[G],G);v!==H&&z.push(j[G])}return z},map:function(j,s,v){for(var z=[],H,G=0,K=j.length;G<K;G++){H=s(j[G],G,v);if(H!=null)z[z.length]=H}return z.concat.apply([],z)},guid:1,proxy:function(j,s,v){if(arguments.length===2)if(typeof s==="string"){v=j;j=v[s];s=B}else if(s&&!b.isFunction(s)){v= s;s=B}if(!s&&j)s=function(){return j.apply(v||this,arguments)};if(j)s.guid=j.guid=j.guid||s.guid||b.guid++;return s},access:function(j,s,v,z,H,G){var K=j.length;if(typeof s==="object"){for(var Q in s)b.access(j,Q,s[Q],z,H,v);return j}if(v!==B){z=!G&&z&&b.isFunction(v);for(Q=0;Q<K;Q++)H(j[Q],s,z?v.call(j[Q],Q,H(j[Q],s)):v,G);return j}return K?H(j[0],s):B},now:function(){return(new Date).getTime()},uaMatch:function(j){j=j.toLowerCase();j=L.exec(j)||g.exec(j)||i.exec(j)||j.indexOf("compatible")<0&&n.exec(j)|| [];return{browser:j[1]||"",version:j[2]||"0"}},browser:{}});b.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(j,s){R["[object "+s+"]"]=s.toLowerCase()});m=b.uaMatch(m);if(m.browser){b.browser[m.browser]=true;b.browser.version=m.version}if(b.browser.webkit)b.browser.safari=true;if(D)b.inArray=function(j,s){return D.call(s,j)};if(!/\s/.test("\u00a0")){k=/^[\s\xA0]+/;o=/[\s\xA0]+$/}f=b(t);if(t.addEventListener)u=function(){t.removeEventListener("DOMContentLoaded",u, false);b.ready()};else if(t.attachEvent)u=function(){if(t.readyState==="complete"){t.detachEvent("onreadystatechange",u);b.ready()}};return E.jQuery=E.$=b}();(function(){c.support={};var a=t.documentElement,b=t.createElement("script"),d=t.createElement("div"),e="script"+c.now();d.style.display="none";d.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";var f=d.getElementsByTagName("*"),h=d.getElementsByTagName("a")[0],l=t.createElement("select"), k=l.appendChild(t.createElement("option"));if(!(!f||!f.length||!h)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(h.getAttribute("style")),hrefNormalized:h.getAttribute("href")==="/a",opacity:/^0.55$/.test(h.style.opacity),cssFloat:!!h.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:k.selected,deleteExpando:true,optDisabled:false,checkClone:false, scriptEval:false,noCloneEvent:true,boxModel:null,inlineBlockNeedsLayout:false,shrinkWrapBlocks:false,reliableHiddenOffsets:true};l.disabled=true;c.support.optDisabled=!k.disabled;b.type="text/javascript";try{b.appendChild(t.createTextNode("window."+e+"=1;"))}catch(o){}a.insertBefore(b,a.firstChild);if(E[e]){c.support.scriptEval=true;delete E[e]}try{delete b.test}catch(x){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function r(){c.support.noCloneEvent= false;d.detachEvent("onclick",r)});d.cloneNode(true).fireEvent("onclick")}d=t.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=t.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var r=t.createElement("div");r.style.width=r.style.paddingLeft="1px";t.body.appendChild(r);c.boxModel=c.support.boxModel=r.offsetWidth===2;if("zoom"in r.style){r.style.display="inline";r.style.zoom= 1;c.support.inlineBlockNeedsLayout=r.offsetWidth===2;r.style.display="";r.innerHTML="<div style='width:4px;'></div>";c.support.shrinkWrapBlocks=r.offsetWidth!==2}r.innerHTML="<table><tr><td style='padding:0;display:none'></td><td>t</td></tr></table>";var A=r.getElementsByTagName("td");c.support.reliableHiddenOffsets=A[0].offsetHeight===0;A[0].style.display="";A[1].style.display="none";c.support.reliableHiddenOffsets=c.support.reliableHiddenOffsets&&A[0].offsetHeight===0;r.innerHTML="";t.body.removeChild(r).style.display= "none"});a=function(r){var A=t.createElement("div");r="on"+r;var C=r in A;if(!C){A.setAttribute(r,"return;");C=typeof A[r]==="function"}return C};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=f=h=null}})();var ra={},Ja=/^(?:\{.*\}|\[.*\])$/;c.extend({cache:{},uuid:0,expando:"jQuery"+c.now(),noData:{embed:true,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:true},data:function(a,b,d){if(c.acceptData(a)){a=a==E?ra:a;var e=a.nodeType,f=e?a[c.expando]:null,h= c.cache;if(!(e&&!f&&typeof b==="string"&&d===B)){if(e)f||(a[c.expando]=f=++c.uuid);else h=a;if(typeof b==="object")if(e)h[f]=c.extend(h[f],b);else c.extend(h,b);else if(e&&!h[f])h[f]={};a=e?h[f]:h;if(d!==B)a[b]=d;return typeof b==="string"?a[b]:a}}},removeData:function(a,b){if(c.acceptData(a)){a=a==E?ra:a;var d=a.nodeType,e=d?a[c.expando]:a,f=c.cache,h=d?f[e]:e;if(b){if(h){delete h[b];d&&c.isEmptyObject(h)&&c.removeData(a)}}else if(d&&c.support.deleteExpando)delete a[c.expando];else if(a.removeAttribute)a.removeAttribute(c.expando); else if(d)delete f[e];else for(var l in a)delete a[l]}},acceptData:function(a){if(a.nodeName){var b=c.noData[a.nodeName.toLowerCase()];if(b)return!(b===true||a.getAttribute("classid")!==b)}return true}});c.fn.extend({data:function(a,b){var d=null;if(typeof a==="undefined"){if(this.length){var e=this[0].attributes,f;d=c.data(this[0]);for(var h=0,l=e.length;h<l;h++){f=e[h].name;if(f.indexOf("data-")===0){f=f.substr(5);ka(this[0],f,d[f])}}}return d}else if(typeof a==="object")return this.each(function(){c.data(this, a)});var k=a.split(".");k[1]=k[1]?"."+k[1]:"";if(b===B){d=this.triggerHandler("getData"+k[1]+"!",[k[0]]);if(d===B&&this.length){d=c.data(this[0],a);d=ka(this[0],a,d)}return d===B&&k[1]?this.data(k[0]):d}else return this.each(function(){var o=c(this),x=[k[0],b];o.triggerHandler("setData"+k[1]+"!",x);c.data(this,a,b);o.triggerHandler("changeData"+k[1]+"!",x)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var e= c.data(a,b);if(!d)return e||[];if(!e||c.isArray(d))e=c.data(a,b,c.makeArray(d));else e.push(d);return e}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),e=d.shift();if(e==="inprogress")e=d.shift();if(e){b==="fx"&&d.unshift("inprogress");e.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b===B)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this, a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var sa=/[\n\t]/g,ha=/\s+/,Sa=/\r/g,Ta=/^(?:href|src|style)$/,Ua=/^(?:button|input)$/i,Va=/^(?:button|input|object|select|textarea)$/i,Wa=/^a(?:rea)?$/i,ta=/^(?:radio|checkbox)$/i;c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan", colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};c.fn.extend({attr:function(a,b){return c.access(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(x){var r=c(this);r.addClass(a.call(this,x,r.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ha),d=0,e=this.length;d<e;d++){var f=this[d];if(f.nodeType=== 1)if(f.className){for(var h=" "+f.className+" ",l=f.className,k=0,o=b.length;k<o;k++)if(h.indexOf(" "+b[k]+" ")<0)l+=" "+b[k];f.className=c.trim(l)}else f.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(o){var x=c(this);x.removeClass(a.call(this,o,x.attr("class")))});if(a&&typeof a==="string"||a===B)for(var b=(a||"").split(ha),d=0,e=this.length;d<e;d++){var f=this[d];if(f.nodeType===1&&f.className)if(a){for(var h=(" "+f.className+" ").replace(sa," "), l=0,k=b.length;l<k;l++)h=h.replace(" "+b[l]+" "," ");f.className=c.trim(h)}else f.className=""}return this},toggleClass:function(a,b){var d=typeof a,e=typeof b==="boolean";if(c.isFunction(a))return this.each(function(f){var h=c(this);h.toggleClass(a.call(this,f,h.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var f,h=0,l=c(this),k=b,o=a.split(ha);f=o[h++];){k=e?k:!l.hasClass(f);l[k?"addClass":"removeClass"](f)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this, "__className__",this.className);this.className=this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(sa," ").indexOf(a)>-1)return true;return false},val:function(a){if(!arguments.length){var b=this[0];if(b){if(c.nodeName(b,"option")){var d=b.attributes.value;return!d||d.specified?b.value:b.text}if(c.nodeName(b,"select")){var e=b.selectedIndex;d=[];var f=b.options;b=b.type==="select-one"; if(e<0)return null;var h=b?e:0;for(e=b?e+1:f.length;h<e;h++){var l=f[h];if(l.selected&&(c.support.optDisabled?!l.disabled:l.getAttribute("disabled")===null)&&(!l.parentNode.disabled||!c.nodeName(l.parentNode,"optgroup"))){a=c(l).val();if(b)return a;d.push(a)}}return d}if(ta.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Sa,"")}return B}var k=c.isFunction(a);return this.each(function(o){var x=c(this),r=a;if(this.nodeType===1){if(k)r= a.call(this,o,x.val());if(r==null)r="";else if(typeof r==="number")r+="";else if(c.isArray(r))r=c.map(r,function(C){return C==null?"":C+""});if(c.isArray(r)&&ta.test(this.type))this.checked=c.inArray(x.val(),r)>=0;else if(c.nodeName(this,"select")){var A=c.makeArray(r);c("option",this).each(function(){this.selected=c.inArray(c(this).val(),A)>=0});if(!A.length)this.selectedIndex=-1}else this.value=r}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true}, attr:function(a,b,d,e){if(!a||a.nodeType===3||a.nodeType===8)return B;if(e&&b in c.attrFn)return c(a)[b](d);e=a.nodeType!==1||!c.isXMLDoc(a);var f=d!==B;b=e&&c.props[b]||b;var h=Ta.test(b);if((b in a||a[b]!==B)&&e&&!h){if(f){b==="type"&&Ua.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed");if(d===null)a.nodeType===1&&a.removeAttribute(b);else a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&& b.specified?b.value:Va.test(a.nodeName)||Wa.test(a.nodeName)&&a.href?0:B;return a[b]}if(!c.support.style&&e&&b==="style"){if(f)a.style.cssText=""+d;return a.style.cssText}f&&a.setAttribute(b,""+d);if(!a.attributes[b]&&a.hasAttribute&&!a.hasAttribute(b))return B;a=!c.support.hrefNormalized&&e&&h?a.getAttribute(b,2):a.getAttribute(b);return a===null?B:a}});var X=/\.(.*)$/,ia=/^(?:textarea|input|select)$/i,La=/\./g,Ma=/ /g,Xa=/[^\w\s.|`]/g,Ya=function(a){return a.replace(Xa,"\\$&")},ua={focusin:0,focusout:0}; c.event={add:function(a,b,d,e){if(!(a.nodeType===3||a.nodeType===8)){if(c.isWindow(a)&&a!==E&&!a.frameElement)a=E;if(d===false)d=U;else if(!d)return;var f,h;if(d.handler){f=d;d=f.handler}if(!d.guid)d.guid=c.guid++;if(h=c.data(a)){var l=a.nodeType?"events":"__events__",k=h[l],o=h.handle;if(typeof k==="function"){o=k.handle;k=k.events}else if(!k){a.nodeType||(h[l]=h=function(){});h.events=k={}}if(!o)h.handle=o=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(o.elem, arguments):B};o.elem=a;b=b.split(" ");for(var x=0,r;l=b[x++];){h=f?c.extend({},f):{handler:d,data:e};if(l.indexOf(".")>-1){r=l.split(".");l=r.shift();h.namespace=r.slice(0).sort().join(".")}else{r=[];h.namespace=""}h.type=l;if(!h.guid)h.guid=d.guid;var A=k[l],C=c.event.special[l]||{};if(!A){A=k[l]=[];if(!C.setup||C.setup.call(a,e,r,o)===false)if(a.addEventListener)a.addEventListener(l,o,false);else a.attachEvent&&a.attachEvent("on"+l,o)}if(C.add){C.add.call(a,h);if(!h.handler.guid)h.handler.guid= d.guid}A.push(h);c.event.global[l]=true}a=null}}},global:{},remove:function(a,b,d,e){if(!(a.nodeType===3||a.nodeType===8)){if(d===false)d=U;var f,h,l=0,k,o,x,r,A,C,J=a.nodeType?"events":"__events__",w=c.data(a),I=w&&w[J];if(w&&I){if(typeof I==="function"){w=I;I=I.events}if(b&&b.type){d=b.handler;b=b.type}if(!b||typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(f in I)c.event.remove(a,f+b)}else{for(b=b.split(" ");f=b[l++];){r=f;k=f.indexOf(".")<0;o=[];if(!k){o=f.split(".");f=o.shift();x=RegExp("(^|\\.)"+ c.map(o.slice(0).sort(),Ya).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(A=I[f])if(d){r=c.event.special[f]||{};for(h=e||0;h<A.length;h++){C=A[h];if(d.guid===C.guid){if(k||x.test(C.namespace)){e==null&&A.splice(h--,1);r.remove&&r.remove.call(a,C)}if(e!=null)break}}if(A.length===0||e!=null&&A.length===1){if(!r.teardown||r.teardown.call(a,o)===false)c.removeEvent(a,f,w.handle);delete I[f]}}else for(h=0;h<A.length;h++){C=A[h];if(k||x.test(C.namespace)){c.event.remove(a,r,C.handler,h);A.splice(h--,1)}}}if(c.isEmptyObject(I)){if(b= w.handle)b.elem=null;delete w.events;delete w.handle;if(typeof w==="function")c.removeData(a,J);else c.isEmptyObject(w)&&c.removeData(a)}}}}},trigger:function(a,b,d,e){var f=a.type||a;if(!e){a=typeof a==="object"?a[c.expando]?a:c.extend(c.Event(f),a):c.Event(f);if(f.indexOf("!")>=0){a.type=f=f.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[f]&&c.each(c.cache,function(){this.events&&this.events[f]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType=== 8)return B;a.result=B;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(e=d.nodeType?c.data(d,"handle"):(c.data(d,"__events__")||{}).handle)&&e.apply(d,b);e=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+f]&&d["on"+f].apply(d,b)===false){a.result=false;a.preventDefault()}}catch(h){}if(!a.isPropagationStopped()&&e)c.event.trigger(a,b,e,true);else if(!a.isDefaultPrevented()){var l;e=a.target;var k=f.replace(X,""),o=c.nodeName(e,"a")&&k=== "click",x=c.event.special[k]||{};if((!x._default||x._default.call(d,a)===false)&&!o&&!(e&&e.nodeName&&c.noData[e.nodeName.toLowerCase()])){try{if(e[k]){if(l=e["on"+k])e["on"+k]=null;c.event.triggered=true;e[k]()}}catch(r){}if(l)e["on"+k]=l;c.event.triggered=false}}},handle:function(a){var b,d,e,f;d=[];var h=c.makeArray(arguments);a=h[0]=c.event.fix(a||E.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive;if(!b){e=a.type.split(".");a.type=e.shift();d=e.slice(0).sort();e=RegExp("(^|\\.)"+ d.join("\\.(?:.*\\.)?")+"(\\.|$)")}a.namespace=a.namespace||d.join(".");f=c.data(this,this.nodeType?"events":"__events__");if(typeof f==="function")f=f.events;d=(f||{})[a.type];if(f&&d){d=d.slice(0);f=0;for(var l=d.length;f<l;f++){var k=d[f];if(b||e.test(k.namespace)){a.handler=k.handler;a.data=k.data;a.handleObj=k;k=k.handler.apply(this,h);if(k!==B){a.result=k;if(k===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}}return a.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), fix:function(a){if(a[c.expando])return a;var b=a;a=c.Event(b);for(var d=this.props.length,e;d;){e=this.props[--d];a[e]=b[e]}if(!a.target)a.target=a.srcElement||t;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=t.documentElement;d=t.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop|| d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(a.which==null&&(a.charCode!=null||a.keyCode!=null))a.which=a.charCode!=null?a.charCode:a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==B)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a){c.event.add(this,Y(a.origType,a.selector),c.extend({},a,{handler:Ka,guid:a.handler.guid}))},remove:function(a){c.event.remove(this, Y(a.origType,a.selector),a)}},beforeunload:{setup:function(a,b,d){if(c.isWindow(this))this.onbeforeunload=d},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};c.removeEvent=t.removeEventListener?function(a,b,d){a.removeEventListener&&a.removeEventListener(b,d,false)}:function(a,b,d){a.detachEvent&&a.detachEvent("on"+b,d)};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent=a;this.type=a.type}else this.type=a;this.timeStamp= c.now();this[c.expando]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=ca;var a=this.originalEvent;if(a)if(a.preventDefault)a.preventDefault();else a.returnValue=false},stopPropagation:function(){this.isPropagationStopped=ca;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=ca;this.stopPropagation()},isDefaultPrevented:U,isPropagationStopped:U,isImmediatePropagationStopped:U}; var va=function(a){var b=a.relatedTarget;try{for(;b&&b!==this;)b=b.parentNode;if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}}catch(d){}},wa=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?wa:va,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?wa:va)}}});if(!c.support.submitBubbles)c.event.special.submit={setup:function(){if(this.nodeName.toLowerCase()!== "form"){c.event.add(this,"click.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="submit"||d==="image")&&c(b).closest("form").length){a.liveFired=B;return la("submit",this,arguments)}});c.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="text"||d==="password")&&c(b).closest("form").length&&a.keyCode===13){a.liveFired=B;return la("submit",this,arguments)}})}else return false},teardown:function(){c.event.remove(this,".specialSubmit")}};if(!c.support.changeBubbles){var V, xa=function(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(e){return e.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},Z=function(a,b){var d=a.target,e,f;if(!(!ia.test(d.nodeName)||d.readOnly)){e=c.data(d,"_change_data");f=xa(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data",f);if(!(e===B||f===e))if(e!=null||f){a.type="change";a.liveFired= B;return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:Z,beforedeactivate:Z,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return Z.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return Z.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a,"_change_data",xa(a))}},setup:function(){if(this.type=== "file")return false;for(var a in V)c.event.add(this,a+".specialChange",V[a]);return ia.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return ia.test(this.nodeName)}};V=c.event.special.change.filters;V.focus=V.beforeactivate}t.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(e){e=c.event.fix(e);e.type=b;return c.event.trigger(e,null,e.target)}c.event.special[b]={setup:function(){ua[b]++===0&&t.addEventListener(a,d,true)},teardown:function(){--ua[b]=== 0&&t.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,e,f){if(typeof d==="object"){for(var h in d)this[b](h,e,d[h],f);return this}if(c.isFunction(e)||e===false){f=e;e=B}var l=b==="one"?c.proxy(f,function(o){c(this).unbind(o,l);return f.apply(this,arguments)}):f;if(d==="unload"&&b!=="one")this.one(d,e,f);else{h=0;for(var k=this.length;h<k;h++)c.event.add(this[h],d,l,e)}return this}});c.fn.extend({unbind:function(a,b){if(typeof a==="object"&&!a.preventDefault)for(var d in a)this.unbind(d, a[d]);else{d=0;for(var e=this.length;d<e;d++)c.event.remove(this[d],a,b)}return this},delegate:function(a,b,d,e){return this.live(b,d,e,a)},undelegate:function(a,b,d){return arguments.length===0?this.unbind("live"):this.die(b,null,d,a)},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){var d=c.Event(a);d.preventDefault();d.stopPropagation();c.event.trigger(d,b,this[0]);return d.result}},toggle:function(a){for(var b=arguments,d= 1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(e){var f=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,f+1);e.preventDefault();return b[f].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var ya={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};c.each(["live","die"],function(a,b){c.fn[b]=function(d,e,f,h){var l,k=0,o,x,r=h||this.selector;h=h?this:c(this.context);if(typeof d=== "object"&&!d.preventDefault){for(l in d)h[b](l,e,d[l],r);return this}if(c.isFunction(e)){f=e;e=B}for(d=(d||"").split(" ");(l=d[k++])!=null;){o=X.exec(l);x="";if(o){x=o[0];l=l.replace(X,"")}if(l==="hover")d.push("mouseenter"+x,"mouseleave"+x);else{o=l;if(l==="focus"||l==="blur"){d.push(ya[l]+x);l+=x}else l=(ya[l]||l)+x;if(b==="live"){x=0;for(var A=h.length;x<A;x++)c.event.add(h[x],"live."+Y(l,r),{data:e,selector:r,handler:f,origType:l,origHandler:f,preType:o})}else h.unbind("live."+Y(l,r),f)}}return this}}); c.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "),function(a,b){c.fn[b]=function(d,e){if(e==null){e=d;d=null}return arguments.length>0?this.bind(b,d,e):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});E.attachEvent&&!E.addEventListener&&c(E).bind("unload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}}); (function(){function a(g,i,n,m,p,q){p=0;for(var u=m.length;p<u;p++){var y=m[p];if(y){var F=false;for(y=y[g];y;){if(y.sizcache===n){F=m[y.sizset];break}if(y.nodeType===1&&!q){y.sizcache=n;y.sizset=p}if(y.nodeName.toLowerCase()===i){F=y;break}y=y[g]}m[p]=F}}}function b(g,i,n,m,p,q){p=0;for(var u=m.length;p<u;p++){var y=m[p];if(y){var F=false;for(y=y[g];y;){if(y.sizcache===n){F=m[y.sizset];break}if(y.nodeType===1){if(!q){y.sizcache=n;y.sizset=p}if(typeof i!=="string"){if(y===i){F=true;break}}else if(k.filter(i, [y]).length>0){F=y;break}}y=y[g]}m[p]=F}}}var d=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,e=0,f=Object.prototype.toString,h=false,l=true;[0,0].sort(function(){l=false;return 0});var k=function(g,i,n,m){n=n||[];var p=i=i||t;if(i.nodeType!==1&&i.nodeType!==9)return[];if(!g||typeof g!=="string")return n;var q,u,y,F,M,N=true,O=k.isXML(i),D=[],R=g;do{d.exec("");if(q=d.exec(R)){R=q[3];D.push(q[1]);if(q[2]){F=q[3]; break}}}while(q);if(D.length>1&&x.exec(g))if(D.length===2&&o.relative[D[0]])u=L(D[0]+D[1],i);else for(u=o.relative[D[0]]?[i]:k(D.shift(),i);D.length;){g=D.shift();if(o.relative[g])g+=D.shift();u=L(g,u)}else{if(!m&&D.length>1&&i.nodeType===9&&!O&&o.match.ID.test(D[0])&&!o.match.ID.test(D[D.length-1])){q=k.find(D.shift(),i,O);i=q.expr?k.filter(q.expr,q.set)[0]:q.set[0]}if(i){q=m?{expr:D.pop(),set:C(m)}:k.find(D.pop(),D.length===1&&(D[0]==="~"||D[0]==="+")&&i.parentNode?i.parentNode:i,O);u=q.expr?k.filter(q.expr, q.set):q.set;if(D.length>0)y=C(u);else N=false;for(;D.length;){q=M=D.pop();if(o.relative[M])q=D.pop();else M="";if(q==null)q=i;o.relative[M](y,q,O)}}else y=[]}y||(y=u);y||k.error(M||g);if(f.call(y)==="[object Array]")if(N)if(i&&i.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&k.contains(i,y[g])))n.push(u[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&n.push(u[g]);else n.push.apply(n,y);else C(y,n);if(F){k(F,p,n,m);k.uniqueSort(n)}return n};k.uniqueSort=function(g){if(w){h= l;g.sort(w);if(h)for(var i=1;i<g.length;i++)g[i]===g[i-1]&&g.splice(i--,1)}return g};k.matches=function(g,i){return k(g,null,null,i)};k.matchesSelector=function(g,i){return k(i,null,null,[g]).length>0};k.find=function(g,i,n){var m;if(!g)return[];for(var p=0,q=o.order.length;p<q;p++){var u,y=o.order[p];if(u=o.leftMatch[y].exec(g)){var F=u[1];u.splice(1,1);if(F.substr(F.length-1)!=="\\"){u[1]=(u[1]||"").replace(/\\/g,"");m=o.find[y](u,i,n);if(m!=null){g=g.replace(o.match[y],"");break}}}}m||(m=i.getElementsByTagName("*")); return{set:m,expr:g}};k.filter=function(g,i,n,m){for(var p,q,u=g,y=[],F=i,M=i&&i[0]&&k.isXML(i[0]);g&&i.length;){for(var N in o.filter)if((p=o.leftMatch[N].exec(g))!=null&&p[2]){var O,D,R=o.filter[N];D=p[1];q=false;p.splice(1,1);if(D.substr(D.length-1)!=="\\"){if(F===y)y=[];if(o.preFilter[N])if(p=o.preFilter[N](p,F,n,y,m,M)){if(p===true)continue}else q=O=true;if(p)for(var j=0;(D=F[j])!=null;j++)if(D){O=R(D,p,j,F);var s=m^!!O;if(n&&O!=null)if(s)q=true;else F[j]=false;else if(s){y.push(D);q=true}}if(O!== B){n||(F=y);g=g.replace(o.match[N],"");if(!q)return[];break}}}if(g===u)if(q==null)k.error(g);else break;u=g}return F};k.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var o=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/, POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}},relative:{"+":function(g,i){var n=typeof i==="string",m=n&&!/\W/.test(i);n=n&&!m;if(m)i=i.toLowerCase();m=0;for(var p=g.length,q;m<p;m++)if(q=g[m]){for(;(q=q.previousSibling)&&q.nodeType!==1;);g[m]=n||q&&q.nodeName.toLowerCase()=== i?q||false:q===i}n&&k.filter(i,g,true)},">":function(g,i){var n,m=typeof i==="string",p=0,q=g.length;if(m&&!/\W/.test(i))for(i=i.toLowerCase();p<q;p++){if(n=g[p]){n=n.parentNode;g[p]=n.nodeName.toLowerCase()===i?n:false}}else{for(;p<q;p++)if(n=g[p])g[p]=m?n.parentNode:n.parentNode===i;m&&k.filter(i,g,true)}},"":function(g,i,n){var m,p=e++,q=b;if(typeof i==="string"&&!/\W/.test(i)){m=i=i.toLowerCase();q=a}q("parentNode",i,p,g,m,n)},"~":function(g,i,n){var m,p=e++,q=b;if(typeof i==="string"&&!/\W/.test(i)){m= i=i.toLowerCase();q=a}q("previousSibling",i,p,g,m,n)}},find:{ID:function(g,i,n){if(typeof i.getElementById!=="undefined"&&!n)return(g=i.getElementById(g[1]))&&g.parentNode?[g]:[]},NAME:function(g,i){if(typeof i.getElementsByName!=="undefined"){for(var n=[],m=i.getElementsByName(g[1]),p=0,q=m.length;p<q;p++)m[p].getAttribute("name")===g[1]&&n.push(m[p]);return n.length===0?null:n}},TAG:function(g,i){return i.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,i,n,m,p,q){g=" "+g[1].replace(/\\/g, "")+" ";if(q)return g;q=0;for(var u;(u=i[q])!=null;q++)if(u)if(p^(u.className&&(" "+u.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))n||m.push(u);else if(n)i[q]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()},CHILD:function(g){if(g[1]==="nth"){var i=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=i[1]+(i[2]||1)-0;g[3]=i[3]-0}g[0]=e++;return g},ATTR:function(g,i,n, m,p,q){i=g[1].replace(/\\/g,"");if(!q&&o.attrMap[i])g[1]=o.attrMap[i];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,i,n,m,p){if(g[1]==="not")if((d.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=k(g[3],null,null,i);else{g=k.filter(g[3],i,n,true^p);n||m.push.apply(m,g);return false}else if(o.match.POS.test(g[0])||o.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled=== true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,i,n){return!!k(n[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)},text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"=== g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}},setFilters:{first:function(g,i){return i===0},last:function(g,i,n,m){return i===m.length-1},even:function(g,i){return i%2===0},odd:function(g,i){return i%2===1},lt:function(g,i,n){return i<n[3]-0},gt:function(g,i,n){return i>n[3]-0},nth:function(g,i,n){return n[3]- 0===i},eq:function(g,i,n){return n[3]-0===i}},filter:{PSEUDO:function(g,i,n,m){var p=i[1],q=o.filters[p];if(q)return q(g,n,i,m);else if(p==="contains")return(g.textContent||g.innerText||k.getText([g])||"").indexOf(i[3])>=0;else if(p==="not"){i=i[3];n=0;for(m=i.length;n<m;n++)if(i[n]===g)return false;return true}else k.error("Syntax error, unrecognized expression: "+p)},CHILD:function(g,i){var n=i[1],m=g;switch(n){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(n=== "first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":n=i[2];var p=i[3];if(n===1&&p===0)return true;var q=i[0],u=g.parentNode;if(u&&(u.sizcache!==q||!g.nodeIndex)){var y=0;for(m=u.firstChild;m;m=m.nextSibling)if(m.nodeType===1)m.nodeIndex=++y;u.sizcache=q}m=g.nodeIndex-p;return n===0?m===0:m%n===0&&m/n>=0}},ID:function(g,i){return g.nodeType===1&&g.getAttribute("id")===i},TAG:function(g,i){return i==="*"&&g.nodeType===1||g.nodeName.toLowerCase()=== i},CLASS:function(g,i){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(i)>-1},ATTR:function(g,i){var n=i[1];n=o.attrHandle[n]?o.attrHandle[n](g):g[n]!=null?g[n]:g.getAttribute(n);var m=n+"",p=i[2],q=i[4];return n==null?p==="!=":p==="="?m===q:p==="*="?m.indexOf(q)>=0:p==="~="?(" "+m+" ").indexOf(q)>=0:!q?m&&n!==false:p==="!="?m!==q:p==="^="?m.indexOf(q)===0:p==="$="?m.substr(m.length-q.length)===q:p==="|="?m===q||m.substr(0,q.length+1)===q+"-":false},POS:function(g,i,n,m){var p=o.setFilters[i[2]]; if(p)return p(g,n,i,m)}}},x=o.match.POS,r=function(g,i){return"\\"+(i-0+1)},A;for(A in o.match){o.match[A]=RegExp(o.match[A].source+/(?![^\[]*\])(?![^\(]*\))/.source);o.leftMatch[A]=RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[A].source.replace(/\\(\d+)/g,r))}var C=function(g,i){g=Array.prototype.slice.call(g,0);if(i){i.push.apply(i,g);return i}return g};try{Array.prototype.slice.call(t.documentElement.childNodes,0)}catch(J){C=function(g,i){var n=0,m=i||[];if(f.call(g)==="[object Array]")Array.prototype.push.apply(m, g);else if(typeof g.length==="number")for(var p=g.length;n<p;n++)m.push(g[n]);else for(;g[n];n++)m.push(g[n]);return m}}var w,I;if(t.documentElement.compareDocumentPosition)w=function(g,i){if(g===i){h=true;return 0}if(!g.compareDocumentPosition||!i.compareDocumentPosition)return g.compareDocumentPosition?-1:1;return g.compareDocumentPosition(i)&4?-1:1};else{w=function(g,i){var n,m,p=[],q=[];n=g.parentNode;m=i.parentNode;var u=n;if(g===i){h=true;return 0}else if(n===m)return I(g,i);else if(n){if(!m)return 1}else return-1; for(;u;){p.unshift(u);u=u.parentNode}for(u=m;u;){q.unshift(u);u=u.parentNode}n=p.length;m=q.length;for(u=0;u<n&&u<m;u++)if(p[u]!==q[u])return I(p[u],q[u]);return u===n?I(g,q[u],-1):I(p[u],i,1)};I=function(g,i,n){if(g===i)return n;for(g=g.nextSibling;g;){if(g===i)return-1;g=g.nextSibling}return 1}}k.getText=function(g){for(var i="",n,m=0;g[m];m++){n=g[m];if(n.nodeType===3||n.nodeType===4)i+=n.nodeValue;else if(n.nodeType!==8)i+=k.getText(n.childNodes)}return i};(function(){var g=t.createElement("div"), i="script"+(new Date).getTime(),n=t.documentElement;g.innerHTML="<a name='"+i+"'/>";n.insertBefore(g,n.firstChild);if(t.getElementById(i)){o.find.ID=function(m,p,q){if(typeof p.getElementById!=="undefined"&&!q)return(p=p.getElementById(m[1]))?p.id===m[1]||typeof p.getAttributeNode!=="undefined"&&p.getAttributeNode("id").nodeValue===m[1]?[p]:B:[]};o.filter.ID=function(m,p){var q=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&q&&q.nodeValue===p}}n.removeChild(g); n=g=null})();(function(){var g=t.createElement("div");g.appendChild(t.createComment(""));if(g.getElementsByTagName("*").length>0)o.find.TAG=function(i,n){var m=n.getElementsByTagName(i[1]);if(i[1]==="*"){for(var p=[],q=0;m[q];q++)m[q].nodeType===1&&p.push(m[q]);m=p}return m};g.innerHTML="<a href='#'></a>";if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")o.attrHandle.href=function(i){return i.getAttribute("href",2)};g=null})();t.querySelectorAll&& function(){var g=k,i=t.createElement("div");i.innerHTML="<p class='TEST'></p>";if(!(i.querySelectorAll&&i.querySelectorAll(".TEST").length===0)){k=function(m,p,q,u){p=p||t;m=m.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!u&&!k.isXML(p))if(p.nodeType===9)try{return C(p.querySelectorAll(m),q)}catch(y){}else if(p.nodeType===1&&p.nodeName.toLowerCase()!=="object"){var F=p.getAttribute("id"),M=F||"__sizzle__";F||p.setAttribute("id",M);try{return C(p.querySelectorAll("#"+M+" "+m),q)}catch(N){}finally{F|| p.removeAttribute("id")}}return g(m,p,q,u)};for(var n in g)k[n]=g[n];i=null}}();(function(){var g=t.documentElement,i=g.matchesSelector||g.mozMatchesSelector||g.webkitMatchesSelector||g.msMatchesSelector,n=false;try{i.call(t.documentElement,"[test!='']:sizzle")}catch(m){n=true}if(i)k.matchesSelector=function(p,q){q=q.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!k.isXML(p))try{if(n||!o.match.PSEUDO.test(q)&&!/!=/.test(q))return i.call(p,q)}catch(u){}return k(q,null,null,[p]).length>0}})();(function(){var g= t.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){o.order.splice(1,0,"CLASS");o.find.CLASS=function(i,n,m){if(typeof n.getElementsByClassName!=="undefined"&&!m)return n.getElementsByClassName(i[1])};g=null}}})();k.contains=t.documentElement.contains?function(g,i){return g!==i&&(g.contains?g.contains(i):true)}:t.documentElement.compareDocumentPosition? function(g,i){return!!(g.compareDocumentPosition(i)&16)}:function(){return false};k.isXML=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false};var L=function(g,i){for(var n,m=[],p="",q=i.nodeType?[i]:i;n=o.match.PSEUDO.exec(g);){p+=n[0];g=g.replace(o.match.PSEUDO,"")}g=o.relative[g]?g+"*":g;n=0;for(var u=q.length;n<u;n++)k(g,q[n],m);return k.filter(p,m)};c.find=k;c.expr=k.selectors;c.expr[":"]=c.expr.filters;c.unique=k.uniqueSort;c.text=k.getText;c.isXMLDoc=k.isXML; c.contains=k.contains})();var Za=/Until$/,$a=/^(?:parents|prevUntil|prevAll)/,ab=/,/,Na=/^.[^:#\[\.,]*$/,bb=Array.prototype.slice,cb=c.expr.match.POS;c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,e=0,f=this.length;e<f;e++){d=b.length;c.find(a,this[e],b);if(e>0)for(var h=d;h<b.length;h++)for(var l=0;l<d;l++)if(b[l]===b[h]){b.splice(h--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,e=b.length;d<e;d++)if(c.contains(this,b[d]))return true})}, not:function(a){return this.pushStack(ma(this,a,false),"not",a)},filter:function(a){return this.pushStack(ma(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){var d=[],e,f,h=this[0];if(c.isArray(a)){var l,k={},o=1;if(h&&a.length){e=0;for(f=a.length;e<f;e++){l=a[e];k[l]||(k[l]=c.expr.match.POS.test(l)?c(l,b||this.context):l)}for(;h&&h.ownerDocument&&h!==b;){for(l in k){e=k[l];if(e.jquery?e.index(h)>-1:c(h).is(e))d.push({selector:l,elem:h,level:o})}h= h.parentNode;o++}}return d}l=cb.test(a)?c(a,b||this.context):null;e=0;for(f=this.length;e<f;e++)for(h=this[e];h;)if(l?l.index(h)>-1:c.find.matchesSelector(h,a)){d.push(h);break}else{h=h.parentNode;if(!h||!h.ownerDocument||h===b)break}d=d.length>1?c.unique(d):d;return this.pushStack(d,"closest",a)},index:function(a){if(!a||typeof a==="string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var d=typeof a==="string"?c(a,b||this.context): c.makeArray(a),e=c.merge(this.get(),d);return this.pushStack(!d[0]||!d[0].parentNode||d[0].parentNode.nodeType===11||!e[0]||!e[0].parentNode||e[0].parentNode.nodeType===11?e:c.unique(e))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode",d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a, 2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a, b){c.fn[a]=function(d,e){var f=c.map(this,b,d);Za.test(a)||(e=d);if(e&&typeof e==="string")f=c.filter(e,f);f=this.length>1?c.unique(f):f;if((this.length>1||ab.test(e))&&$a.test(a))f=f.reverse();return this.pushStack(f,a,bb.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return b.length===1?c.find.matchesSelector(b[0],a)?[b[0]]:[]:c.find.matches(a,b)},dir:function(a,b,d){var e=[];for(a=a[b];a&&a.nodeType!==9&&(d===B||a.nodeType!==1||!c(a).is(d));){a.nodeType===1&& e.push(a);a=a[b]}return e},nth:function(a,b,d){b=b||1;for(var e=0;a;a=a[d])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var za=/ jQuery\d+="(?:\d+|null)"/g,$=/^\s+/,Aa=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Ba=/<([\w:]+)/,db=/<tbody/i,eb=/<|&#?\w+;/,Ca=/<(?:script|object|embed|option|style)/i,Da=/checked\s*(?:[^=]|=\s*.checked.)/i,fb=/\=([^="'>\s]+\/)>/g,P={option:[1, "<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};P.optgroup=P.option;P.tbody=P.tfoot=P.colgroup=P.caption=P.thead;P.th=P.td;if(!c.support.htmlSerialize)P._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d= c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==B)return this.empty().append((this[0]&&this[0].ownerDocument||t).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this}, wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})}, prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b, this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,e;(e=this[d])!=null;d++)if(!a||c.filter(a,[e]).length){if(!b&&e.nodeType===1){c.cleanData(e.getElementsByTagName("*"));c.cleanData([e])}e.parentNode&&e.parentNode.removeChild(e)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChild;)b.removeChild(b.firstChild); return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,e=this.ownerDocument;if(!d){d=e.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(za,"").replace(fb,'="$1">').replace($,"")],e)[0]}else return this.cloneNode(true)});if(a===true){na(this,b);na(this.find("*"),b.find("*"))}return b},html:function(a){if(a===B)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(za,""):null; else if(typeof a==="string"&&!Ca.test(a)&&(c.support.leadingWhitespace||!$.test(a))&&!P[(Ba.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Aa,"<$1></$2>");try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(e){this.empty().append(a)}}else c.isFunction(a)?this.each(function(f){var h=c(this);h.html(a.call(this,f,h.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d= c(this),e=d.html();d.replaceWith(a.call(this,b,e))});if(typeof a!=="string")a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){var e,f,h,l=a[0],k=[];if(!c.support.checkClone&&arguments.length===3&&typeof l==="string"&&Da.test(l))return this.each(function(){c(this).domManip(a, b,d,true)});if(c.isFunction(l))return this.each(function(x){var r=c(this);a[0]=l.call(this,x,b?r.html():B);r.domManip(a,b,d)});if(this[0]){e=l&&l.parentNode;e=c.support.parentNode&&e&&e.nodeType===11&&e.childNodes.length===this.length?{fragment:e}:c.buildFragment(a,this,k);h=e.fragment;if(f=h.childNodes.length===1?h=h.firstChild:h.firstChild){b=b&&c.nodeName(f,"tr");f=0;for(var o=this.length;f<o;f++)d.call(b?c.nodeName(this[f],"table")?this[f].getElementsByTagName("tbody")[0]||this[f].appendChild(this[f].ownerDocument.createElement("tbody")): this[f]:this[f],f>0||e.cacheable||this.length>1?h.cloneNode(true):h)}k.length&&c.each(k,Oa)}return this}});c.buildFragment=function(a,b,d){var e,f,h;b=b&&b[0]?b[0].ownerDocument||b[0]:t;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&b===t&&!Ca.test(a[0])&&(c.support.checkClone||!Da.test(a[0]))){f=true;if(h=c.fragments[a[0]])if(h!==1)e=h}if(!e){e=b.createDocumentFragment();c.clean(a,b,e,d)}if(f)c.fragments[a[0]]=h?e:1;return{fragment:e,cacheable:f}};c.fragments={};c.each({appendTo:"append", prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var e=[];d=c(d);var f=this.length===1&&this[0].parentNode;if(f&&f.nodeType===11&&f.childNodes.length===1&&d.length===1){d[b](this[0]);return this}else{f=0;for(var h=d.length;f<h;f++){var l=(f>0?this.clone(true):this).get();c(d[f])[b](l);e=e.concat(l)}return this.pushStack(e,a,d.selector)}}});c.extend({clean:function(a,b,d,e){b=b||t;if(typeof b.createElement==="undefined")b=b.ownerDocument|| b[0]&&b[0].ownerDocument||t;for(var f=[],h=0,l;(l=a[h])!=null;h++){if(typeof l==="number")l+="";if(l){if(typeof l==="string"&&!eb.test(l))l=b.createTextNode(l);else if(typeof l==="string"){l=l.replace(Aa,"<$1></$2>");var k=(Ba.exec(l)||["",""])[1].toLowerCase(),o=P[k]||P._default,x=o[0],r=b.createElement("div");for(r.innerHTML=o[1]+l+o[2];x--;)r=r.lastChild;if(!c.support.tbody){x=db.test(l);k=k==="table"&&!x?r.firstChild&&r.firstChild.childNodes:o[1]==="<table>"&&!x?r.childNodes:[];for(o=k.length- 1;o>=0;--o)c.nodeName(k[o],"tbody")&&!k[o].childNodes.length&&k[o].parentNode.removeChild(k[o])}!c.support.leadingWhitespace&&$.test(l)&&r.insertBefore(b.createTextNode($.exec(l)[0]),r.firstChild);l=r.childNodes}if(l.nodeType)f.push(l);else f=c.merge(f,l)}}if(d)for(h=0;f[h];h++)if(e&&c.nodeName(f[h],"script")&&(!f[h].type||f[h].type.toLowerCase()==="text/javascript"))e.push(f[h].parentNode?f[h].parentNode.removeChild(f[h]):f[h]);else{f[h].nodeType===1&&f.splice.apply(f,[h+1,0].concat(c.makeArray(f[h].getElementsByTagName("script")))); d.appendChild(f[h])}return f},cleanData:function(a){for(var b,d,e=c.cache,f=c.event.special,h=c.support.deleteExpando,l=0,k;(k=a[l])!=null;l++)if(!(k.nodeName&&c.noData[k.nodeName.toLowerCase()]))if(d=k[c.expando]){if((b=e[d])&&b.events)for(var o in b.events)f[o]?c.event.remove(k,o):c.removeEvent(k,o,b.handle);if(h)delete k[c.expando];else k.removeAttribute&&k.removeAttribute(c.expando);delete e[d]}}});var Ea=/alpha\([^)]*\)/i,gb=/opacity=([^)]*)/,hb=/-([a-z])/ig,ib=/([A-Z])/g,Fa=/^-?\d+(?:px)?$/i, jb=/^-?\d/,kb={position:"absolute",visibility:"hidden",display:"block"},Pa=["Left","Right"],Qa=["Top","Bottom"],W,Ga,aa,lb=function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){if(arguments.length===2&&b===B)return this;return c.access(this,a,b,true,function(d,e,f){return f!==B?c.style(d,e,f):c.css(d,e)})};c.extend({cssHooks:{opacity:{get:function(a,b){if(b){var d=W(a,"opacity","opacity");return d===""?"1":d}else return a.style.opacity}}},cssNumber:{zIndex:true,fontWeight:true,opacity:true, zoom:true,lineHeight:true},cssProps:{"float":c.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,d,e){if(!(!a||a.nodeType===3||a.nodeType===8||!a.style)){var f,h=c.camelCase(b),l=a.style,k=c.cssHooks[h];b=c.cssProps[h]||h;if(d!==B){if(!(typeof d==="number"&&isNaN(d)||d==null)){if(typeof d==="number"&&!c.cssNumber[h])d+="px";if(!k||!("set"in k)||(d=k.set(a,d))!==B)try{l[b]=d}catch(o){}}}else{if(k&&"get"in k&&(f=k.get(a,false,e))!==B)return f;return l[b]}}},css:function(a,b,d){var e,f=c.camelCase(b), h=c.cssHooks[f];b=c.cssProps[f]||f;if(h&&"get"in h&&(e=h.get(a,true,d))!==B)return e;else if(W)return W(a,b,f)},swap:function(a,b,d){var e={},f;for(f in b){e[f]=a.style[f];a.style[f]=b[f]}d.call(a);for(f in b)a.style[f]=e[f]},camelCase:function(a){return a.replace(hb,lb)}});c.curCSS=c.css;c.each(["height","width"],function(a,b){c.cssHooks[b]={get:function(d,e,f){var h;if(e){if(d.offsetWidth!==0)h=oa(d,b,f);else c.swap(d,kb,function(){h=oa(d,b,f)});if(h<=0){h=W(d,b,b);if(h==="0px"&&aa)h=aa(d,b,b); if(h!=null)return h===""||h==="auto"?"0px":h}if(h<0||h==null){h=d.style[b];return h===""||h==="auto"?"0px":h}return typeof h==="string"?h:h+"px"}},set:function(d,e){if(Fa.test(e)){e=parseFloat(e);if(e>=0)return e+"px"}else return e}}});if(!c.support.opacity)c.cssHooks.opacity={get:function(a,b){return gb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var d=a.style;d.zoom=1;var e=c.isNaN(b)?"":"alpha(opacity="+b*100+")",f= d.filter||"";d.filter=Ea.test(f)?f.replace(Ea,e):d.filter+" "+e}};if(t.defaultView&&t.defaultView.getComputedStyle)Ga=function(a,b,d){var e;d=d.replace(ib,"-$1").toLowerCase();if(!(b=a.ownerDocument.defaultView))return B;if(b=b.getComputedStyle(a,null)){e=b.getPropertyValue(d);if(e===""&&!c.contains(a.ownerDocument.documentElement,a))e=c.style(a,d)}return e};if(t.documentElement.currentStyle)aa=function(a,b){var d,e,f=a.currentStyle&&a.currentStyle[b],h=a.style;if(!Fa.test(f)&&jb.test(f)){d=h.left; e=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;h.left=b==="fontSize"?"1em":f||0;f=h.pixelLeft+"px";h.left=d;a.runtimeStyle.left=e}return f===""?"auto":f};W=Ga||aa;if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b=a.offsetHeight;return a.offsetWidth===0&&b===0||!c.support.reliableHiddenOffsets&&(a.style.display||c.css(a,"display"))==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var mb=c.now(),nb=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, ob=/^(?:select|textarea)/i,pb=/^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,qb=/^(?:GET|HEAD)$/,Ra=/\[\]$/,T=/\=\?(&|$)/,ja=/\?/,rb=/([?&])_=[^&]*/,sb=/^(\w+:)?\/\/([^\/?#]+)/,tb=/%20/g,ub=/#.*$/,Ha=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!=="string"&&Ha)return Ha.apply(this,arguments);else if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var f=a.slice(e,a.length);a=a.slice(0,e)}e="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b=== "object"){b=c.param(b,c.ajaxSettings.traditional);e="POST"}var h=this;c.ajax({url:a,type:e,dataType:"html",data:b,complete:function(l,k){if(k==="success"||k==="notmodified")h.html(f?c("<div>").append(l.responseText.replace(nb,"")).find(f):l.responseText);d&&h.each(d,[l.responseText,k,l])}});return this},serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&& !this.disabled&&(this.checked||ob.test(this.nodeName)||pb.test(this.type))}).map(function(a,b){var d=c(this).val();return d==null?null:c.isArray(d)?c.map(d,function(e){return{name:b.name,value:e}}):{name:b.name,value:d}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,e){if(c.isFunction(b)){e=e||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:e})}, getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,e){if(c.isFunction(b)){e=e||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:e})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return new E.XMLHttpRequest},accepts:{xml:"application/xml, text/xml",html:"text/html", script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},ajax:function(a){var b=c.extend(true,{},c.ajaxSettings,a),d,e,f,h=b.type.toUpperCase(),l=qb.test(h);b.url=b.url.replace(ub,"");b.context=a&&a.context!=null?a.context:b;if(b.data&&b.processData&&typeof b.data!=="string")b.data=c.param(b.data,b.traditional);if(b.dataType==="jsonp"){if(h==="GET")T.test(b.url)||(b.url+=(ja.test(b.url)?"&":"?")+(b.jsonp||"callback")+"=?");else if(!b.data|| !T.test(b.data))b.data=(b.data?b.data+"&":"")+(b.jsonp||"callback")+"=?";b.dataType="json"}if(b.dataType==="json"&&(b.data&&T.test(b.data)||T.test(b.url))){d=b.jsonpCallback||"jsonp"+mb++;if(b.data)b.data=(b.data+"").replace(T,"="+d+"$1");b.url=b.url.replace(T,"="+d+"$1");b.dataType="script";var k=E[d];E[d]=function(m){if(c.isFunction(k))k(m);else{E[d]=B;try{delete E[d]}catch(p){}}f=m;c.handleSuccess(b,w,e,f);c.handleComplete(b,w,e,f);r&&r.removeChild(A)}}if(b.dataType==="script"&&b.cache===null)b.cache= false;if(b.cache===false&&l){var o=c.now(),x=b.url.replace(rb,"$1_="+o);b.url=x+(x===b.url?(ja.test(b.url)?"&":"?")+"_="+o:"")}if(b.data&&l)b.url+=(ja.test(b.url)?"&":"?")+b.data;b.global&&c.active++===0&&c.event.trigger("ajaxStart");o=(o=sb.exec(b.url))&&(o[1]&&o[1].toLowerCase()!==location.protocol||o[2].toLowerCase()!==location.host);if(b.dataType==="script"&&h==="GET"&&o){var r=t.getElementsByTagName("head")[0]||t.documentElement,A=t.createElement("script");if(b.scriptCharset)A.charset=b.scriptCharset; A.src=b.url;if(!d){var C=false;A.onload=A.onreadystatechange=function(){if(!C&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){C=true;c.handleSuccess(b,w,e,f);c.handleComplete(b,w,e,f);A.onload=A.onreadystatechange=null;r&&A.parentNode&&r.removeChild(A)}}}r.insertBefore(A,r.firstChild);return B}var J=false,w=b.xhr();if(w){b.username?w.open(h,b.url,b.async,b.username,b.password):w.open(h,b.url,b.async);try{if(b.data!=null&&!l||a&&a.contentType)w.setRequestHeader("Content-Type", b.contentType);if(b.ifModified){c.lastModified[b.url]&&w.setRequestHeader("If-Modified-Since",c.lastModified[b.url]);c.etag[b.url]&&w.setRequestHeader("If-None-Match",c.etag[b.url])}o||w.setRequestHeader("X-Requested-With","XMLHttpRequest");w.setRequestHeader("Accept",b.dataType&&b.accepts[b.dataType]?b.accepts[b.dataType]+", */*; q=0.01":b.accepts._default)}catch(I){}if(b.beforeSend&&b.beforeSend.call(b.context,w,b)===false){b.global&&c.active--===1&&c.event.trigger("ajaxStop");w.abort();return false}b.global&& c.triggerGlobal(b,"ajaxSend",[w,b]);var L=w.onreadystatechange=function(m){if(!w||w.readyState===0||m==="abort"){J||c.handleComplete(b,w,e,f);J=true;if(w)w.onreadystatechange=c.noop}else if(!J&&w&&(w.readyState===4||m==="timeout")){J=true;w.onreadystatechange=c.noop;e=m==="timeout"?"timeout":!c.httpSuccess(w)?"error":b.ifModified&&c.httpNotModified(w,b.url)?"notmodified":"success";var p;if(e==="success")try{f=c.httpData(w,b.dataType,b)}catch(q){e="parsererror";p=q}if(e==="success"||e==="notmodified")d|| c.handleSuccess(b,w,e,f);else c.handleError(b,w,e,p);d||c.handleComplete(b,w,e,f);m==="timeout"&&w.abort();if(b.async)w=null}};try{var g=w.abort;w.abort=function(){w&&Function.prototype.call.call(g,w);L("abort")}}catch(i){}b.async&&b.timeout>0&&setTimeout(function(){w&&!J&&L("timeout")},b.timeout);try{w.send(l||b.data==null?null:b.data)}catch(n){c.handleError(b,w,null,n);c.handleComplete(b,w,e,f)}b.async||L();return w}},param:function(a,b){var d=[],e=function(h,l){l=c.isFunction(l)?l():l;d[d.length]= encodeURIComponent(h)+"="+encodeURIComponent(l)};if(b===B)b=c.ajaxSettings.traditional;if(c.isArray(a)||a.jquery)c.each(a,function(){e(this.name,this.value)});else for(var f in a)da(f,a[f],b,e);return d.join("&").replace(tb,"+")}});c.extend({active:0,lastModified:{},etag:{},handleError:function(a,b,d,e){a.error&&a.error.call(a.context,b,d,e);a.global&&c.triggerGlobal(a,"ajaxError",[b,a,e])},handleSuccess:function(a,b,d,e){a.success&&a.success.call(a.context,e,d,b);a.global&&c.triggerGlobal(a,"ajaxSuccess", [b,a])},handleComplete:function(a,b,d){a.complete&&a.complete.call(a.context,b,d);a.global&&c.triggerGlobal(a,"ajaxComplete",[b,a]);a.global&&c.active--===1&&c.event.trigger("ajaxStop")},triggerGlobal:function(a,b,d){(a.context&&a.context.url==null?c(a.context):c.event).trigger(b,d)},httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status===1223}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"), e=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(e)c.etag[b]=e;return a.status===304},httpData:function(a,b,d){var e=a.getResponseHeader("content-type")||"",f=b==="xml"||!b&&e.indexOf("xml")>=0;a=f?a.responseXML:a.responseText;f&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b==="json"||!b&&e.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&e.indexOf("javascript")>=0)c.globalEval(a);return a}}); if(E.ActiveXObject)c.ajaxSettings.xhr=function(){if(E.location.protocol!=="file:")try{return new E.XMLHttpRequest}catch(a){}try{return new E.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}};c.support.ajax=!!c.ajaxSettings.xhr();var ea={},vb=/^(?:toggle|show|hide)$/,wb=/^([+\-]=)?([\d+.\-]+)(.*)$/,ba,pa=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b,d){if(a||a===0)return this.animate(S("show", 3),a,b,d);else{d=0;for(var e=this.length;d<e;d++){a=this[d];b=a.style.display;if(!c.data(a,"olddisplay")&&b==="none")b=a.style.display="";b===""&&c.css(a,"display")==="none"&&c.data(a,"olddisplay",qa(a.nodeName))}for(d=0;d<e;d++){a=this[d];b=a.style.display;if(b===""||b==="none")a.style.display=c.data(a,"olddisplay")||""}return this}},hide:function(a,b,d){if(a||a===0)return this.animate(S("hide",3),a,b,d);else{a=0;for(b=this.length;a<b;a++){d=c.css(this[a],"display");d!=="none"&&c.data(this[a],"olddisplay", d)}for(a=0;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b,d){var e=typeof a==="boolean";if(c.isFunction(a)&&c.isFunction(b))this._toggle.apply(this,arguments);else a==null||e?this.each(function(){var f=e?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(S("toggle",3),a,b,d);return this},fadeTo:function(a,b,d,e){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d,e)},animate:function(a,b,d,e){var f=c.speed(b, d,e);if(c.isEmptyObject(a))return this.each(f.complete);return this[f.queue===false?"each":"queue"](function(){var h=c.extend({},f),l,k=this.nodeType===1,o=k&&c(this).is(":hidden"),x=this;for(l in a){var r=c.camelCase(l);if(l!==r){a[r]=a[l];delete a[l];l=r}if(a[l]==="hide"&&o||a[l]==="show"&&!o)return h.complete.call(this);if(k&&(l==="height"||l==="width")){h.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY];if(c.css(this,"display")==="inline"&&c.css(this,"float")==="none")if(c.support.inlineBlockNeedsLayout)if(qa(this.nodeName)=== "inline")this.style.display="inline-block";else{this.style.display="inline";this.style.zoom=1}else this.style.display="inline-block"}if(c.isArray(a[l])){(h.specialEasing=h.specialEasing||{})[l]=a[l][1];a[l]=a[l][0]}}if(h.overflow!=null)this.style.overflow="hidden";h.curAnim=c.extend({},a);c.each(a,function(A,C){var J=new c.fx(x,h,A);if(vb.test(C))J[C==="toggle"?o?"show":"hide":C](a);else{var w=wb.exec(C),I=J.cur()||0;if(w){var L=parseFloat(w[2]),g=w[3]||"px";if(g!=="px"){c.style(x,A,(L||1)+g);I=(L|| 1)/J.cur()*I;c.style(x,A,I+g)}if(w[1])L=(w[1]==="-="?-1:1)*L+I;J.custom(I,L,g)}else J.custom(I,C,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]);this.each(function(){for(var e=d.length-1;e>=0;e--)if(d[e].elem===this){b&&d[e](true);d.splice(e,1)}});b||this.dequeue();return this}});c.each({slideDown:S("show",1),slideUp:S("hide",1),slideToggle:S("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){c.fn[a]=function(d,e,f){return this.animate(b, d,e,f)}});c.extend({speed:function(a,b,d){var e=a&&typeof a==="object"?c.extend({},a):{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};e.duration=c.fx.off?0:typeof e.duration==="number"?e.duration:e.duration in c.fx.speeds?c.fx.speeds[e.duration]:c.fx.speeds._default;e.old=e.complete;e.complete=function(){e.queue!==false&&c(this).dequeue();c.isFunction(e.old)&&e.old.call(this)};return e},easing:{linear:function(a,b,d,e){return d+e*a},swing:function(a,b,d,e){return(-Math.cos(a* Math.PI)/2+0.5)*e+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]||c.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a=parseFloat(c.css(this.elem,this.prop));return a&&a>-1E4?a:0},custom:function(a,b,d){function e(l){return f.step(l)} var f=this,h=c.fx;this.startTime=c.now();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start;this.pos=this.state=0;e.elem=this.elem;if(e()&&c.timers.push(e)&&!ba)ba=setInterval(h.tick,h.interval)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true; this.custom(this.cur(),0)},step:function(a){var b=c.now(),d=true;if(a||b>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var e in this.options.curAnim)if(this.options.curAnim[e]!==true)d=false;if(d){if(this.options.overflow!=null&&!c.support.shrinkWrapBlocks){var f=this.elem,h=this.options;c.each(["","X","Y"],function(k,o){f.style["overflow"+o]=h.overflow[k]})}this.options.hide&&c(this.elem).hide();if(this.options.hide|| this.options.show)for(var l in this.options.curAnim)c.style(this.elem,l,this.options.orig[l]);this.options.complete.call(this.elem)}return false}else{a=b-this.startTime;this.state=a/this.options.duration;b=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||b](this.state,a,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a= c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||c.fx.stop()},interval:13,stop:function(){clearInterval(ba);ba=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!=null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a=== b.elem}).length};var xb=/^t(?:able|d|h)$/i,Ia=/^(?:body|html)$/i;c.fn.offset="getBoundingClientRect"in t.documentElement?function(a){var b=this[0],d;if(a)return this.each(function(l){c.offset.setOffset(this,a,l)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);try{d=b.getBoundingClientRect()}catch(e){}var f=b.ownerDocument,h=f.documentElement;if(!d||!c.contains(h,b))return d||{top:0,left:0};b=f.body;f=fa(f);return{top:d.top+(f.pageYOffset||c.support.boxModel&& h.scrollTop||b.scrollTop)-(h.clientTop||b.clientTop||0),left:d.left+(f.pageXOffset||c.support.boxModel&&h.scrollLeft||b.scrollLeft)-(h.clientLeft||b.clientLeft||0)}}:function(a){var b=this[0];if(a)return this.each(function(x){c.offset.setOffset(this,a,x)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d,e=b.offsetParent,f=b.ownerDocument,h=f.documentElement,l=f.body;d=(f=f.defaultView)?f.getComputedStyle(b,null):b.currentStyle; for(var k=b.offsetTop,o=b.offsetLeft;(b=b.parentNode)&&b!==l&&b!==h;){if(c.offset.supportsFixedPosition&&d.position==="fixed")break;d=f?f.getComputedStyle(b,null):b.currentStyle;k-=b.scrollTop;o-=b.scrollLeft;if(b===e){k+=b.offsetTop;o+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&xb.test(b.nodeName))){k+=parseFloat(d.borderTopWidth)||0;o+=parseFloat(d.borderLeftWidth)||0}e=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&d.overflow!=="visible"){k+= parseFloat(d.borderTopWidth)||0;o+=parseFloat(d.borderLeftWidth)||0}d=d}if(d.position==="relative"||d.position==="static"){k+=l.offsetTop;o+=l.offsetLeft}if(c.offset.supportsFixedPosition&&d.position==="fixed"){k+=Math.max(h.scrollTop,l.scrollTop);o+=Math.max(h.scrollLeft,l.scrollLeft)}return{top:k,left:o}};c.offset={initialize:function(){var a=t.body,b=t.createElement("div"),d,e,f,h=parseFloat(c.css(a,"marginTop"))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px", height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";a.insertBefore(b,a.firstChild);d=b.firstChild;e=d.firstChild;f=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=e.offsetTop!==5;this.doesAddBorderForTableAndCells= f.offsetTop===5;e.style.position="fixed";e.style.top="20px";this.supportsFixedPosition=e.offsetTop===20||e.offsetTop===15;e.style.position=e.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=e.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==h;a.removeChild(b);c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.css(a, "marginTop"))||0;d+=parseFloat(c.css(a,"marginLeft"))||0}return{top:b,left:d}},setOffset:function(a,b,d){var e=c.css(a,"position");if(e==="static")a.style.position="relative";var f=c(a),h=f.offset(),l=c.css(a,"top"),k=c.css(a,"left"),o=e==="absolute"&&c.inArray("auto",[l,k])>-1;e={};var x={};if(o)x=f.position();l=o?x.top:parseInt(l,10)||0;k=o?x.left:parseInt(k,10)||0;if(c.isFunction(b))b=b.call(a,d,h);if(b.top!=null)e.top=b.top-h.top+l;if(b.left!=null)e.left=b.left-h.left+k;"using"in b?b.using.call(a, e):f.css(e)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),e=Ia.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.css(a,"marginTop"))||0;d.left-=parseFloat(c.css(a,"marginLeft"))||0;e.top+=parseFloat(c.css(b[0],"borderTopWidth"))||0;e.left+=parseFloat(c.css(b[0],"borderLeftWidth"))||0;return{top:d.top-e.top,left:d.left-e.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||t.body;a&&!Ia.test(a.nodeName)&& c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(e){var f=this[0],h;if(!f)return null;if(e!==B)return this.each(function(){if(h=fa(this))h.scrollTo(!a?e:c(h).scrollLeft(),a?e:c(h).scrollTop());else this[d]=e});else return(h=fa(f))?"pageXOffset"in h?h[a?"pageYOffset":"pageXOffset"]:c.support.boxModel&&h.document.documentElement[d]||h.document.body[d]:f[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase(); c.fn["inner"+b]=function(){return this[0]?parseFloat(c.css(this[0],d,"padding")):null};c.fn["outer"+b]=function(e){return this[0]?parseFloat(c.css(this[0],d,e?"margin":"border")):null};c.fn[d]=function(e){var f=this[0];if(!f)return e==null?null:this;if(c.isFunction(e))return this.each(function(l){var k=c(this);k[d](e.call(this,l,k[d]()))});if(c.isWindow(f))return f.document.compatMode==="CSS1Compat"&&f.document.documentElement["client"+b]||f.document.body["client"+b];else if(f.nodeType===9)return Math.max(f.documentElement["client"+ b],f.body["scroll"+b],f.documentElement["scroll"+b],f.body["offset"+b],f.documentElement["offset"+b]);else if(e===B){f=c.css(f,d);var h=parseFloat(f);return c.isNaN(h)?f:h}else return this.css(d,typeof e==="string"?e:e+"px")}})})(window);
src/App/components/UserNameInput.react.js
Rezmodeus/Multiplikation
import React from 'react'; import ReactDOM from 'react-dom'; const MAX_LENGTH = 20; const ENTER_KEY_CODE = 13; export default React.createClass({ onKeyUp(event){ let val = event.target.value; val = val.replace(/[^a-zA-Z]/, '').substring(0, 12); this.refs.textArea.value = val; this.props.setText(val); }, onKeyDown (event) { if (event.keyCode === ENTER_KEY_CODE) { if (!event.shiftKey && !event.ctrlKey) { event.preventDefault(); let text = this.refs.textArea.value; if (text.trim()) { } } } }, render() { return ( <textarea className="name-input" placeholder="Skriv in ett nytt namn här" ref="textArea" rows="1" name="message" onKeyUp={(event)=>this.onKeyUp(event)} maxLength={MAX_LENGTH} /> ); } }); //onKeyDown={(event)=>this.onKeyDown(event)} //onChange={(event)=>this.onChange(event)}
components/MdButton/MdButton.js
Ineigo/react-library-components
import React from 'react'; import PropTypes from 'prop-types'; import style from './style.m.less'; import classNames from 'classnames'; import LoaderHelper from '../../helpers/LoaderHelper'; class MdButton extends React.Component { static propTypes = { type: PropTypes.string, title: PropTypes.string, iconStyle: PropTypes.string, loading: PropTypes.bool, disabled: PropTypes.bool, fontWeight: PropTypes.string, onClick: PropTypes.func.isRequired, onMouseLeave: PropTypes.func, widthStyle: PropTypes.string, extraClasses: PropTypes.string }; getLoaderColor() { let color = '#000'; const type = this.props.type; if (type === 'submit' || type === 'delete') { color = '#fff'; } return color; } render() { const buttonClass = this._getClassNamesForButton(); const titleSpanClass = this._getClassNamesForTitle(); const wrapperDivClass = this._getClassNamesForWrapper(); return ( <div className={wrapperDivClass}> <button className={buttonClass} type='button' onClick={this._onClickButton} onMouseLeave={this._onMouseLeave}> {this.props.loading && this._getLoader()} <span className={titleSpanClass}>{this.props.title}</span> </button> </div> ); } _getLoader() { return (<span className={style['md-button__loader']}> {LoaderHelper.getSmall(this.getLoaderColor())} </span>); } _onClickButton = e => { !this.props.disabled && this.props.onClick(e); }; _onMouseLeave = e => { if (!this.props.disabled && this.props.onMouseLeave) { this.props.onMouseLeave(e); } }; _getClassNamesForButton() { return classNames( style['md-button__body'], { [style[`md-button__body--${this.props.type}`]]: this.props.type, [style['md-button__body--icon']]: this.props.iconStyle, [style['md-button__body--loading']]: this.props.loading, [this.props.extraClasses]: this.props.extraClasses } ); } _getClassNamesForTitle() { return classNames(style['md-button__title'], { [style[`md-button__title--${this.props.iconStyle}`]]: this.props.iconStyle, [style['md-button__title--normalFont']]: this.props.fontWeight === 'normal' }); } _getClassNamesForWrapper() { return classNames(style['md-button'], { [style[`md-button--${this.props.widthStyle}`]]: this.props.widthStyle, [style['md-button--disabled']]: this.props.disabled && !this.props.loading }); } } export default MdButton;
src/svg-icons/navigation/arrow-drop-down.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationArrowDropDown = (props) => ( <SvgIcon {...props}> <path d="M7 10l5 5 5-5z"/> </SvgIcon> ); NavigationArrowDropDown = pure(NavigationArrowDropDown); NavigationArrowDropDown.displayName = 'NavigationArrowDropDown'; export default NavigationArrowDropDown;
dist/vuera.iife.js
akxcv/vuera
var vuera = (function (exports,React,ReactDOM,Vue) { 'use strict'; React = React && React.hasOwnProperty('default') ? React['default'] : React; ReactDOM = ReactDOM && ReactDOM.hasOwnProperty('default') ? ReactDOM['default'] : ReactDOM; Vue = Vue && Vue.hasOwnProperty('default') ? Vue['default'] : Vue; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var defineProperty = function (obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; var objectWithoutProperties = function (obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }; var possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; var 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 VUE_COMPONENT_NAME = 'vuera-internal-component-name'; var wrapReactChildren = function wrapReactChildren(createElement, children) { return createElement('vuera-internal-react-wrapper', { props: { component: function component() { return React.createElement( 'div', null, children ); } } }); }; var VueContainer = function (_React$Component) { inherits(VueContainer, _React$Component); function VueContainer(props) { classCallCheck(this, VueContainer); /** * We have to track the current Vue component so that we can reliably catch updates to the * `component` prop. */ var _this = possibleConstructorReturn(this, (VueContainer.__proto__ || Object.getPrototypeOf(VueContainer)).call(this, props)); _this.currentVueComponent = props.component; /** * Modify createVueInstance function to pass this binding correctly. Doing this in the * constructor to avoid instantiating functions in render. */ var createVueInstance = _this.createVueInstance; var self = _this; _this.createVueInstance = function (element, component, prevComponent) { createVueInstance(element, self, component, prevComponent); }; return _this; } createClass(VueContainer, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { var component = nextProps.component, props = objectWithoutProperties(nextProps, ['component']); if (this.currentVueComponent !== component) { this.updateVueComponent(this.props.component, component); } /** * NOTE: we're not comparing this.props and nextProps here, because I didn't want to write a * function for deep object comparison. I don't know if this hurts performance a lot, maybe * we do need to compare those objects. */ Object.assign(this.vueInstance.$data, props); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.vueInstance.$destroy(); } /** * Creates and mounts the Vue instance. * NOTE: since we need to access the current instance of VueContainer, as well as the Vue instance * inside of the Vue constructor, we cannot bind this function to VueContainer, and we need to * pass VueContainer's binding explicitly. * @param {HTMLElement} targetElement - element to attact the Vue instance to * @param {ReactInstance} reactThisBinding - current instance of VueContainer */ }, { key: 'createVueInstance', value: function createVueInstance(targetElement, reactThisBinding) { var _components; var _reactThisBinding$pro = reactThisBinding.props, component = _reactThisBinding$pro.component, on = _reactThisBinding$pro.on, props = objectWithoutProperties(_reactThisBinding$pro, ['component', 'on']); // `this` refers to Vue instance in the constructor reactThisBinding.vueInstance = new Vue(_extends({ el: targetElement, data: props }, config.vueInstanceOptions, { render: function render(createElement) { return createElement(VUE_COMPONENT_NAME, { props: this.$data, on: on }, [wrapReactChildren(createElement, this.children)]); }, components: (_components = {}, defineProperty(_components, VUE_COMPONENT_NAME, component), defineProperty(_components, 'vuera-internal-react-wrapper', ReactWrapper), _components) })); } }, { key: 'updateVueComponent', value: function updateVueComponent(prevComponent, nextComponent) { this.currentVueComponent = nextComponent; /** * Replace the component in the Vue instance and update it. */ this.vueInstance.$options.components[VUE_COMPONENT_NAME] = nextComponent; this.vueInstance.$forceUpdate(); } }, { key: 'render', value: function render() { return React.createElement('div', { ref: this.createVueInstance }); } }]); return VueContainer; }(React.Component); var makeReactContainer = function makeReactContainer(Component) { var _class, _temp; return _temp = _class = function (_React$Component) { inherits(ReactInVue, _React$Component); function ReactInVue(props) { classCallCheck(this, ReactInVue); /** * We create a stateful component in order to attach a ref on it. We will use that ref to * update component's state, which seems better than re-rendering the whole thing with * ReactDOM. */ var _this = possibleConstructorReturn(this, (ReactInVue.__proto__ || Object.getPrototypeOf(ReactInVue)).call(this, props)); _this.state = _extends({}, props); return _this; } createClass(ReactInVue, [{ key: 'wrapVueChildren', value: function wrapVueChildren(children) { return { render: function render(createElement) { return createElement('div', children); } }; } }, { key: 'render', value: function render() { var _state = this.state, children = _state.children, _invoker = _state[''], rest = objectWithoutProperties(_state, ['children', '']); var wrappedChildren = this.wrapVueChildren(children); return React.createElement( Component, rest, children && React.createElement(VueContainer, { component: wrappedChildren }) ); } }]); return ReactInVue; }(React.Component), _class.displayName = 'ReactInVue' + (Component.displayName || Component.name || 'Component'), _temp; }; var ReactWrapper = { props: ['component', 'passedProps'], render: function render(createElement) { return createElement('div', { ref: 'react' }); }, methods: { mountReactComponent: function mountReactComponent(component) { var _this2 = this; var Component = makeReactContainer(component); var children = this.$slots.default !== undefined ? { children: this.$slots.default } : {}; ReactDOM.render(React.createElement(Component, _extends({}, this.$props.passedProps, this.$attrs, this.$listeners, children, { ref: function ref(_ref) { return _this2.reactComponentRef = _ref; } })), this.$refs.react); } }, mounted: function mounted() { this.mountReactComponent(this.$props.component); }, beforeDestroy: function beforeDestroy() { ReactDOM.unmountComponentAtNode(this.$refs.react); }, updated: function updated() { /** * AFAIK, this is the only way to update children. It doesn't seem to be possible to watch * `$slots` or `$children`. */ if (this.$slots.default !== undefined) { this.reactComponentRef.setState({ children: this.$slots.default }); } else { this.reactComponentRef.setState({ children: null }); } }, inheritAttrs: false, watch: { $attrs: { handler: function handler() { this.reactComponentRef.setState(_extends({}, this.$attrs)); }, deep: true }, '$props.component': { handler: function handler(newValue) { this.mountReactComponent(newValue); } }, $listeners: { handler: function handler() { this.reactComponentRef.setState(_extends({}, this.$listeners)); }, deep: true }, '$props.passedProps': { handler: function handler() { this.reactComponentRef.setState(_extends({}, this.$props.passedProps)); }, deep: true } } }; function isReactComponent(component) { if ((typeof component === 'undefined' ? 'undefined' : _typeof(component)) === 'object' && !isReactForwardReference(component)) { return false; } return !(typeof component === 'function' && component.prototype && (component.prototype.constructor.super && component.prototype.constructor.super.isVue || component.prototype instanceof Vue)); } function isReactForwardReference(component) { return component.$$typeof && component.$$typeof.toString() === 'Symbol(react.forward_ref)'; } function VueResolver$$1(component) { return { components: { ReactWrapper: ReactWrapper }, props: ['passedProps'], inheritAttrs: false, render: function render(createElement) { return createElement('react-wrapper', { props: { component: component, passedProps: this.$props.passedProps }, attrs: this.$attrs, on: this.$listeners }, this.$slots.default); } }; } /** * This mixin automatically wraps all React components into Vue. */ var VuePlugin = { install: function install(Vue$$1, options) { /** * We define a custom merging strategy for the `components` field. This strategy really just * wraps all the React components while leaving Vue components as is. */ var originalComponentsMergeStrategy = Vue$$1.config.optionMergeStrategies.components; Vue$$1.config.optionMergeStrategies.components = function (parent) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var mergedValue = originalComponentsMergeStrategy.apply(undefined, [parent].concat(args)); var wrappedComponents = mergedValue ? Object.entries(mergedValue).reduce(function (acc, _ref) { var _ref2 = slicedToArray(_ref, 2), k = _ref2[0], v = _ref2[1]; return _extends({}, acc, defineProperty({}, k, isReactComponent(v) ? VueResolver$$1(v) : v)); }, {}) : mergedValue; return Object.assign(mergedValue, wrappedComponents); }; Vue$$1.prototype.constructor.isVue = true; } }; /* eslint-disable prefer-object-spread/prefer-object-spread */ function ReactResolver$$1(component) { return isReactComponent(component) ? component : function (props) { return React.createElement(VueContainer, _extends({}, props, { component: component })); }; } /** * This function gets imported by the babel plugin. It wraps a suspected React element and, if it * isn't a valid React element, wraps it into a Vue container. */ function babelReactResolver$$1(component, props, children) { return isReactComponent(component) ? React.createElement(component, props, children) : React.createElement(VueContainer, Object.assign({ component: component }, props), children); } function defaultConfig() { return { vueInstanceOptions: {} }; } var config = defaultConfig(); exports.ReactWrapper = ReactWrapper; exports.VueWrapper = VueContainer; exports.__vueraReactResolver = babelReactResolver$$1; exports.VuePlugin = VuePlugin; exports.VueInReact = ReactResolver$$1; exports.ReactInVue = VueResolver$$1; exports.config = config; return exports; }({},React,ReactDOM,Vue));
src/NavItem.js
mmarcant/react-bootstrap
import classNames from 'classnames'; import React from 'react'; import SafeAnchor from './SafeAnchor'; import createChainedFunction from './utils/createChainedFunction'; const propTypes = { active: React.PropTypes.bool, disabled: React.PropTypes.bool, role: React.PropTypes.string, href: React.PropTypes.string, onClick: React.PropTypes.func, onSelect: React.PropTypes.func, eventKey: React.PropTypes.any, }; const defaultProps = { active: false, disabled: false }; class NavItem extends React.Component { constructor(props, context) { super(props, context); this.handleClick = this.handleClick.bind(this); } handleClick(e) { if (this.props.onSelect) { e.preventDefault(); if (!this.props.disabled) { this.props.onSelect(this.props.eventKey, e); } } } render() { const { active, disabled, onClick, className, style, ...props } = this.props; delete props.onSelect; delete props.eventKey; // These are injected down by `<Nav>` for building `<SubNav>`s. delete props.activeKey; delete props.activeHref; if (!props.role) { if (props.href === '#') { props.role = 'button'; } } else if (props.role === 'tab') { props['aria-selected'] = active; } return ( <li role="presentation" className={classNames(className, { active, disabled })} style={style} > <SafeAnchor {...props} disabled={disabled} onClick={createChainedFunction(onClick, this.handleClick)} /> </li> ); } } NavItem.propTypes = propTypes; NavItem.defaultProps = defaultProps; export default NavItem;
components/Header/Header.js
whatever555/countries
import React from 'react'; import styled from 'styled-components'; import { VERT_BREAK } from "../../common/styles"; const Hamburger = styled.button` background: none; position: absolute; padding: 0; margin:0; line-height: 1; left: 4px; cursor: pointer; border: none; outline: 0 ; color: #fee; display: inline-block; width: 40px; font-size: 40px z-index:8020; margin: 2px auto 0px; @media screen and (max-height: ${VERT_BREAK}) { margin: 7px auto 0px; font-size: 30px; } ` const MainLink = styled.a` color: #500; ` // TODO add params as props here const Header = ({openMenu}) => ( <div> <Hamburger onClick={openMenu}>&#9776;</Hamburger> </div> ); export default Header;
webserver/src/components/Layout.js
lukedoolittle/moviematch
'use strict'; import React from 'react'; import { Link } from 'react-router'; export default class Layout extends React.Component { render() { return ( <div className="app-container"> <header> movie_match </header> <div className="app-content">{this.props.children}</div> <footer> <p> Staging </p> </footer> </div> ); } }
src/components/TextInputStyledComponents/TextInputStyledComponents.js
alexcondorachi/ps-react-alexc
import React from 'react'; import PropTypes from 'prop-types'; import Label from '../Label'; import styled from 'styled-components'; /** Text input with integrated label to enforce consistency in layout, error display, label placement, and required field marker. */ function TextInput({htmlId, name, label, type = "text", required = false, onChange, placeholder, value, error, children, ...props}) { const Error = styled.div` color: red; ` const Input = styled.input` border: ${error && 'solid 1px red'}; display: block; `; const Fieldset = styled.div` margin-bottom: 16px; `; return ( <Fieldset> <Label htmlFor={htmlId} label={label} required={required} /> <Input id={htmlId} type={type} name={name} placeholder={placeholder} value={value} onChange={onChange} {...props}/> {children} {error && <Error>{error}</Error>} </Fieldset> ); }; TextInput.propTypes = { /** Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing. */ htmlId: PropTypes.string.isRequired, /** Input name. Recommend setting this to match object's property so a single change handler can be used. */ name: PropTypes.string.isRequired, /** Input label */ label: PropTypes.string.isRequired, /** Input type */ type: PropTypes.oneOf(['text', 'number', 'password']), /** Mark label with asterisk if set to true */ required: PropTypes.bool, /** Function to call onChange */ onChange: PropTypes.func.isRequired, /** Placeholder to display when empty */ placeholder: PropTypes.string, /** Value */ value: PropTypes.any, /** String to display when error occurs */ error: PropTypes.string, /** Child component to display next to the input */ children: PropTypes.node }; export default TextInput;
src/pages/clonix.js
vitorbarbosa19/ziro-online
import React from 'react' import BrandGallery from '../components/BrandGallery' export default () => ( <BrandGallery brand='Clonix' /> )
frontend/src/Settings/Indexers/Indexers/Indexers.js
Radarr/Radarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import Card from 'Components/Card'; import FieldSet from 'Components/FieldSet'; import Icon from 'Components/Icon'; import PageSectionContent from 'Components/Page/PageSectionContent'; import { icons } from 'Helpers/Props'; import translate from 'Utilities/String/translate'; import AddIndexerModal from './AddIndexerModal'; import EditIndexerModalConnector from './EditIndexerModalConnector'; import Indexer from './Indexer'; import styles from './Indexers.css'; class Indexers extends Component { // // Lifecycle constructor(props, context) { super(props, context); this.state = { isAddIndexerModalOpen: false, isEditIndexerModalOpen: false }; } // // Listeners onAddIndexerPress = () => { this.setState({ isAddIndexerModalOpen: true }); }; onCloneIndexerPress = (id) => { this.props.dispatchCloneIndexer({ id }); this.setState({ isEditIndexerModalOpen: true }); }; onAddIndexerModalClose = ({ indexerSelected = false } = {}) => { this.setState({ isAddIndexerModalOpen: false, isEditIndexerModalOpen: indexerSelected }); }; onEditIndexerModalClose = () => { this.setState({ isEditIndexerModalOpen: false }); }; // // Render render() { const { items, tagList, dispatchCloneIndexer, onConfirmDeleteIndexer, ...otherProps } = this.props; const { isAddIndexerModalOpen, isEditIndexerModalOpen } = this.state; const showPriority = items.some((index) => index.priority !== 25); return ( <FieldSet legend={translate('Indexers')}> <PageSectionContent errorMessage={translate('UnableToLoadIndexers')} {...otherProps} > <div className={styles.indexers}> { items.map((item) => { return ( <Indexer key={item.id} {...item} tagList={tagList} showPriority={showPriority} onCloneIndexerPress={this.onCloneIndexerPress} onConfirmDeleteIndexer={onConfirmDeleteIndexer} /> ); }) } <Card className={styles.addIndexer} onPress={this.onAddIndexerPress} > <div className={styles.center}> <Icon name={icons.ADD} size={45} /> </div> </Card> </div> <AddIndexerModal isOpen={isAddIndexerModalOpen} onModalClose={this.onAddIndexerModalClose} /> <EditIndexerModalConnector isOpen={isEditIndexerModalOpen} onModalClose={this.onEditIndexerModalClose} /> </PageSectionContent> </FieldSet> ); } } Indexers.propTypes = { isFetching: PropTypes.bool.isRequired, error: PropTypes.object, items: PropTypes.arrayOf(PropTypes.object).isRequired, tagList: PropTypes.arrayOf(PropTypes.object).isRequired, dispatchCloneIndexer: PropTypes.func.isRequired, onConfirmDeleteIndexer: PropTypes.func.isRequired }; export default Indexers;
example/hoc/useNavigation.js
DavidLazic/react-augment
import React, { Component } from 'react'; /** * @description * Higher order component * Component wrapper used for navigation * * @param {Function} WrappedComponent * @return {Object} * @public */ export const useNavigation = (WrappedComponent = () => null) => class UseNavigation extends Component { constructor (props) { super(props); this.onNavigate = this.onNavigate.bind(this); } /** * @description * On navigate to route. * * @param {String} route * @return {Function} * @public */ onNavigate (route) { // navigate fn } render () { return ( <WrappedComponent { ...this.props } navigate={ this.onNavigate } /> ); } };
client/components/LogoutBtn/LogoutBtn.js
Art404/twitter-boiler404
import React from 'react' export default () => ( <div id="LogoutBtn" key="logout"> <a href="/api/logout-twitter"> {'LOG OUT'} </a> </div> )
src/svg-icons/action/flip-to-back.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionFlipToBack = (props) => ( <SvgIcon {...props}> <path d="M9 7H7v2h2V7zm0 4H7v2h2v-2zm0-8c-1.11 0-2 .9-2 2h2V3zm4 12h-2v2h2v-2zm6-12v2h2c0-1.1-.9-2-2-2zm-6 0h-2v2h2V3zM9 17v-2H7c0 1.1.89 2 2 2zm10-4h2v-2h-2v2zm0-4h2V7h-2v2zm0 8c1.1 0 2-.9 2-2h-2v2zM5 7H3v12c0 1.1.89 2 2 2h12v-2H5V7zm10-2h2V3h-2v2zm0 12h2v-2h-2v2z"/> </SvgIcon> ); ActionFlipToBack = pure(ActionFlipToBack); ActionFlipToBack.displayName = 'ActionFlipToBack'; ActionFlipToBack.muiName = 'SvgIcon'; export default ActionFlipToBack;
src/index.js
SteMcLellan/queryman
// Modules import React from 'react'; import { render } from 'react-dom'; // Global CSS import "./assets/css/globals.css"; import './vendor/photon/css/photon.css'; import './vendor/highlight.js/css/atom-one-light.css'; // Grab all components dynamically import { components } from './components/components.js'; // Since we are using HtmlWebpackPlugin WITHOUT a template, we should create our own root node in the body element before rendering into it let root = document.createElement('div'); root.id = "root"; document.body.appendChild( root ); // Now we can render our application into it. Main entry point is always the 'Core' component render( <components.Core />, document.getElementById('root') ); // Hot Module Replacement API if (module.hot) { // If an update is in one of the React components we've included, we can attempt an HMR // Note: we are using the only-hot so the app will NOT forcefully reload if it fails module.hot.accept( './components/components.js', () => { render( <components.Core />, document.getElementById('root') ); }); }
node_modules/enzyme/src/ReactWrapper.js
Shwrndasink/btholt-react-tutorial
import React from 'react'; import ComplexSelector from './ComplexSelector'; import cheerio from 'cheerio'; import flatten from 'lodash/flatten'; import unique from 'lodash/uniq'; import compact from 'lodash/compact'; import createWrapperComponent from './ReactWrapperComponent'; import { instHasClassName, childrenOfInst, parentsOfInst, buildInstPredicate, instEqual, treeFilter, getNode, internalInstanceOrComponent, } from './MountedTraversal'; import { renderWithOptions, Simulate, findDOMNode, unmountComponentAtNode, } from './react-compat'; import { mapNativeEventNames, containsChildrenSubArray, propsOfNode, typeOfNode, displayNameOfNode, } from './Utils'; import { debugInsts, } from './Debug'; import { REACT15 } from './version'; /** * Finds all nodes in the current wrapper nodes' render trees that match the provided predicate * function. * * @param {ReactWrapper} wrapper * @param {Function} predicate * @param {Function} filter * @returns {ReactWrapper} */ function findWhereUnwrapped(wrapper, predicate, filter = treeFilter) { return wrapper.flatMap(n => filter(n.node, predicate)); } /** * Returns a new wrapper instance with only the nodes of the current wrapper instance that match * the provided predicate function. * * @param {ReactWrapper} wrapper * @param {Function} predicate * @returns {ReactWrapper} */ function filterWhereUnwrapped(wrapper, predicate) { return wrapper.wrap(compact(wrapper.nodes.filter(predicate))); } /** * @class ReactWrapper */ export default class ReactWrapper { constructor(nodes, root, options = {}) { if (!global.window && !global.document) { throw new Error( 'It looks like you called `mount()` without a global document being loaded.' ); } if (!root) { const ReactWrapperComponent = createWrapperComponent(nodes, options); this.component = renderWithOptions( <ReactWrapperComponent Component={nodes.type} props={nodes.props} context={options.context} />, options); this.root = this; this.node = this.component.getWrappedComponent(); this.nodes = [this.node]; this.length = 1; } else { this.component = null; this.root = root; if (!Array.isArray(nodes)) { this.node = nodes; this.nodes = [nodes]; } else { this.node = nodes[0]; this.nodes = nodes; } this.length = this.nodes.length; } this.options = options; this.complexSelector = new ComplexSelector( buildInstPredicate, findWhereUnwrapped, childrenOfInst ); } /** * If the root component contained a ref, you can access it here * and get a wrapper around it. * * NOTE: can only be called on a wrapper instance that is also the root instance. * * @param {String} refname * @returns {ReactWrapper} */ ref(refname) { if (this.root !== this) { throw new Error('ReactWrapper::ref(refname) can only be called on the root'); } return this.wrap(this.instance().refs[refname]); } /** * Gets the instance of the component being rendered as the root node passed into `mount()`. * * NOTE: can only be called on a wrapper instance that is also the root instance. * * Example: * ``` * const wrapper = mount(<MyComponent />); * const inst = wrapper.instance(); * expect(inst).to.be.instanceOf(MyComponent); * ``` * @returns {ReactComponent} */ instance() { if (this.root !== this) { throw new Error('ReactWrapper::instance() can only be called on the root'); } return this.component.getInstance(); } /** * Forces a re-render. Useful to run before checking the render output if something external * may be updating the state of the component somewhere. * * NOTE: can only be called on a wrapper instance that is also the root instance. * * @returns {ReactWrapper} */ update() { if (this.root !== this) { // TODO(lmr): this requirement may not be necessary for the ReactWrapper throw new Error('ReactWrapper::update() can only be called on the root'); } this.single(() => { this.component.forceUpdate(); }); return this; } /** * A method that unmounts the component. This can be used to simulate a component going through * and unmount/mount lifecycle. * * @returns {ReactWrapper} */ unmount() { if (this.root !== this) { throw new Error('ReactWrapper::unmount() can only be called on the root'); } this.single(() => { this.component.setState({ mount: false }); }); return this; } /** * A method that re-mounts the component. This can be used to simulate a component going through * an unmount/mount lifecycle. * * @returns {ReactWrapper} */ mount() { if (this.root !== this) { throw new Error('ReactWrapper::mount() can only be called on the root'); } this.single(() => { this.component.setState({ mount: true }); }); return this; } /** * A method that sets the props of the root component, and re-renders. Useful for when you are * wanting to test how the component behaves over time with changing props. Calling this, for * instance, will call the `componentWillReceiveProps` lifecycle method. * * Similar to `setState`, this method accepts a props object and will merge it in with the already * existing props. * * NOTE: can only be called on a wrapper instance that is also the root instance. * * @param {Object} props object * @returns {ReactWrapper} */ setProps(props) { if (this.root !== this) { throw new Error('ReactWrapper::setProps() can only be called on the root'); } this.component.setChildProps(props); return this; } /** * A method to invoke `setState` on the root component instance similar to how you might in the * definition of the component, and re-renders. This method is useful for testing your component * in hard to achieve states, however should be used sparingly. If possible, you should utilize * your component's external API in order to get it into whatever state you want to test, in order * to be as accurate of a test as possible. This is not always practical, however. * * NOTE: can only be called on a wrapper instance that is also the root instance. * * @param {Object} state to merge * @returns {ReactWrapper} */ setState(state) { if (this.root !== this) { throw new Error('ReactWrapper::setState() can only be called on the root'); } this.instance().setState(state); return this; } /** * A method that sets the context of the root component, and re-renders. Useful for when you are * wanting to test how the component behaves over time with changing contexts. * * NOTE: can only be called on a wrapper instance that is also the root instance. * * @param {Object} context object * @returns {ReactWrapper} */ setContext(context) { if (this.root !== this) { throw new Error('ReactWrapper::setContext() can only be called on the root'); } if (!this.options.context) { throw new Error( 'ShallowWrapper::setContext() can only be called on a wrapper that was originally passed ' + 'a context option' ); } this.component.setChildContext(context); return this; } /** * Whether or not a given react element matches the current render tree. * It will determine if the wrapper root node "looks like" the expected * element by checking if all props of the expected element are present * on the wrapper root node and equals to each other. * * Example: * ``` * // MyComponent outputs <div class="foo">Hello</div> * const wrapper = mount(<MyComponent />); * expect(wrapper.matchesElement(<div>Hello</div>)).to.equal(true); * ``` * * @param {ReactElement} node * @returns {Boolean} */ matchesElement(node) { return this.single(() => instEqual(node, this.node, (a, b) => a <= b)); } /** * Whether or not a given react element exists in the mount render tree. * * Example: * ``` * const wrapper = mount(<MyComponent />); * expect(wrapper.contains(<div className="foo bar" />)).to.equal(true); * ``` * * @param {ReactElement|Array<ReactElement>} nodeOrNodes * @returns {Boolean} */ contains(nodeOrNodes) { const predicate = Array.isArray(nodeOrNodes) ? other => containsChildrenSubArray(instEqual, other, nodeOrNodes) : other => instEqual(nodeOrNodes, other); return findWhereUnwrapped(this, predicate).length > 0; } /** * Whether or not a given react element exists in the current render tree. * It will determine if one of the wrappers element "looks like" the expected * element by checking if all props of the expected element are present * on the wrappers element and equals to each other. * * Example: * ``` * // MyComponent outputs <div><div class="foo">Hello</div></div> * const wrapper = mount(<MyComponent />); * expect(wrapper.containsMatchingElement(<div>Hello</div>)).to.equal(true); * ``` * * @param {ReactElement} node * @returns {Boolean} */ containsMatchingElement(node) { const predicate = other => instEqual(node, other, (a, b) => a <= b); return findWhereUnwrapped(this, predicate).length > 0; } /** * Whether or not all the given react elements exists in the current render tree. * It will determine if one of the wrappers element "looks like" the expected * element by checking if all props of the expected element are present * on the wrappers element and equals to each other. * * Example: * ``` * const wrapper = mount(<MyComponent />); * expect(wrapper.containsAllMatchingElements([ * <div>Hello</div>, * <div>Goodbye</div>, * ])).to.equal(true); * ``` * * @param {Array<ReactElement>} nodes * @returns {Boolean} */ containsAllMatchingElements(nodes) { const invertedEquals = (n1, n2) => instEqual(n2, n1, (a, b) => a <= b); const predicate = other => containsChildrenSubArray(invertedEquals, other, nodes); return findWhereUnwrapped(this, predicate).length > 0; } /** * Whether or not one of the given react elements exists in the current render tree. * It will determine if one of the wrappers element "looks like" the expected * element by checking if all props of the expected element are present * on the wrappers element and equals to each other. * * Example: * ``` * const wrapper = mount(<MyComponent />); * expect(wrapper.containsAnyMatchingElements([ * <div>Hello</div>, * <div>Goodbye</div>, * ])).to.equal(true); * ``` * * @param {Array<ReactElement>} nodes * @returns {Boolean} */ containsAnyMatchingElements(nodes) { if (!Array.isArray(nodes)) return false; if (nodes.length <= 0) return false; for (let i = 0; i < nodes.length; i++) { if (this.containsMatchingElement(nodes[i])) { return true; } } return false; } /** * Finds every node in the render tree of the current wrapper that matches the provided selector. * * @param {String|Function} selector * @returns {ReactWrapper} */ find(selector) { return this.complexSelector.find(selector, this); } /** * Returns whether or not current node matches a provided selector. * * NOTE: can only be called on a wrapper of a single node. * * @param {String|Function} selector * @returns {boolean} */ is(selector) { const predicate = buildInstPredicate(selector); return this.single(n => predicate(n)); } /** * Returns true if the component rendered nothing, i.e., null or false. * * @returns {boolean} */ isEmptyRender() { return this.single((n) => { // Stateful components and stateless function components have different internal structures, // so we need to find the correct internal instance, and validate the rendered node type // equals 2, which is the `ReactNodeTypes.EMPTY` value. if (REACT15) { return internalInstanceOrComponent(n)._renderedNodeType === 2; } return findDOMNode(n) === null; }); } /** * Returns a new wrapper instance with only the nodes of the current wrapper instance that match * the provided predicate function. * * @param {Function} predicate * @returns {ReactWrapper} */ filterWhere(predicate) { return filterWhereUnwrapped(this, n => predicate(this.wrap(n))); } /** * Returns a new wrapper instance with only the nodes of the current wrapper instance that match * the provided selector. * * @param {String|Function} selector * @returns {ReactWrapper} */ filter(selector) { const predicate = buildInstPredicate(selector); return filterWhereUnwrapped(this, predicate); } /** * Returns a new wrapper instance with only the nodes of the current wrapper that did not match * the provided selector. Essentially the inverse of `filter`. * * @param {String|Function} selector * @returns {ReactWrapper} */ not(selector) { const predicate = buildInstPredicate(selector); return filterWhereUnwrapped(this, n => !predicate(n)); } /** * Returns a string of the rendered text of the current render tree. This function should be * looked at with skepticism if being used to test what the actual HTML output of the component * will be. If that is what you would like to test, use enzyme's `render` function instead. * * NOTE: can only be called on a wrapper of a single node. * * @returns {String} */ text() { return this.single(n => findDOMNode(n).textContent); } /** * Returns the HTML of the node. * * NOTE: can only be called on a wrapper of a single node. * * @returns {String} */ html() { return this.single(n => { const node = findDOMNode(n); return node === null ? null : node.outerHTML.replace(/\sdata-(reactid|reactroot)+="([^"]*)+"/g, ''); }); } /** * Returns the current node rendered to HTML and wrapped in a CheerioWrapper. * * NOTE: can only be called on a wrapper of a single node. * * @returns {CheerioWrapper} */ render() { const html = this.html(); return html === null ? cheerio() : cheerio.load(html).root(); } /** * Used to simulate events. Pass an eventname and (optionally) event arguments. This method of * testing events should be met with some skepticism. * * @param {String} event * @param {Object} mock (optional) * @returns {ReactWrapper} */ simulate(event, mock = {}) { this.single(n => { const mappedEvent = mapNativeEventNames(event); const eventFn = Simulate[mappedEvent]; if (!eventFn) { throw new TypeError(`ReactWrapper::simulate() event '${event}' does not exist`); } eventFn(findDOMNode(n), mock); }); return this; } /** * Returns the props hash for the root node of the wrapper. * * NOTE: can only be called on a wrapper of a single node. * * @returns {Object} */ props() { return this.single(propsOfNode); } /** * Returns the state hash for the root node of the wrapper. Optionally pass in a prop name and it * will return just that value. * * NOTE: can only be called on a wrapper of a single node. * * @param {String} name (optional) * @returns {*} */ state(name) { if (this.root !== this) { throw new Error('ReactWrapper::state() can only be called on the root'); } const _state = this.single(() => this.instance().state); if (name !== undefined) { return _state[name]; } return _state; } /** * Returns the context hash for the root node of the wrapper. * Optionally pass in a prop name and it will return just that value. * * NOTE: can only be called on a wrapper of a single node. * * @param {String} name (optional) * @returns {*} */ context(name) { if (this.root !== this) { throw new Error('ReactWrapper::context() can only be called on the root'); } const _context = this.single(() => this.instance().context); if (name !== undefined) { return _context[name]; } return _context; } /** * Returns a new wrapper with all of the children of the current wrapper. * * @param {String|Function} [selector] * @returns {ReactWrapper} */ children(selector) { const allChildren = this.flatMap(n => childrenOfInst(n.node)); return selector ? allChildren.filter(selector) : allChildren; } /** * Returns a new wrapper with a specific child * * @param {Number} [index] * @returns {ReactWrapper} */ childAt(index) { return this.single(() => this.children().at(index)); } /** * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node * in the current wrapper. * * NOTE: can only be called on a wrapper of a single node. * * @param {String|Function} [selector] * @returns {ReactWrapper} */ parents(selector) { const allParents = this.wrap(this.single(n => parentsOfInst(n, this.root.node))); return selector ? allParents.filter(selector) : allParents; } /** * Returns a wrapper around the immediate parent of the current node. * * @returns {ReactWrapper} */ parent() { return this.flatMap(n => [n.parents().get(0)]); } /** * * @param {String|Function} selector * @returns {ReactWrapper} */ closest(selector) { return this.is(selector) ? this : this.parents().filter(selector).first(); } /** * Returns the value of prop with the given name of the root node. * * @param {String} propName * @returns {*} */ prop(propName) { return this.props()[propName]; } /** * Returns the key assigned to the current node. * * @returns {String} */ key() { return this.single((n) => getNode(n).key); } /** * Returns the type of the root node of this wrapper. If it's a composite component, this will be * the component constructor. If it's native DOM node, it will be a string. * * @returns {String|Function} */ type() { return this.single(n => typeOfNode(getNode(n))); } /** * Returns the name of the root node of this wrapper. * * In order of precedence => type.displayName -> type.name -> type. * * @returns {String} */ name() { return this.single(n => displayNameOfNode(getNode(n))); } /** * Returns whether or not the current root node has the given class name or not. * * NOTE: can only be called on a wrapper of a single node. * * @param {String} className * @returns {Boolean} */ hasClass(className) { if (className && className.indexOf('.') !== -1) { // eslint-disable-next-line no-console console.warn( 'It looks like you\'re calling `ReactWrapper::hasClass()` with a CSS selector. ' + 'hasClass() expects a class name, not a CSS selector.' ); } return this.single(n => instHasClassName(n, className)); } /** * Iterates through each node of the current wrapper and executes the provided function with a * wrapper around the corresponding node passed in as the first argument. * * @param {Function} fn * @returns {ReactWrapper} */ forEach(fn) { this.nodes.forEach((n, i) => fn.call(this, this.wrap(n), i)); return this; } /** * Maps the current array of nodes to another array. Each node is passed in as a `ReactWrapper` * to the map function. * * @param {Function} fn * @returns {Array} */ map(fn) { return this.nodes.map((n, i) => fn.call(this, this.wrap(n), i)); } /** * Reduces the current array of nodes to another array. * Each node is passed in as a `ShallowWrapper` to the reducer function. * * @param {Function} fn - the reducer function * @param {*} initialValue - the initial value * @returns {*} */ reduce(fn, initialValue) { return this.nodes.reduce( (accum, n, i) => fn.call(this, accum, this.wrap(n), i), initialValue ); } /** * Reduces the current array of nodes to another array, from right to left. Each node is passed * in as a `ShallowWrapper` to the reducer function. * * @param {Function} fn - the reducer function * @param {*} initialValue - the initial value * @returns {*} */ reduceRight(fn, initialValue) { return this.nodes.reduceRight( (accum, n, i) => fn.call(this, accum, this.wrap(n), i), initialValue ); } /** * Returns whether or not any of the nodes in the wrapper match the provided selector. * * @param {Function|String} selector * @returns {Boolean} */ some(selector) { const predicate = buildInstPredicate(selector); return this.nodes.some(predicate); } /** * Returns whether or not any of the nodes in the wrapper pass the provided predicate function. * * @param {Function} predicate * @returns {Boolean} */ someWhere(predicate) { return this.nodes.some((n, i) => predicate.call(this, this.wrap(n), i)); } /** * Returns whether or not all of the nodes in the wrapper match the provided selector. * * @param {Function|String} selector * @returns {Boolean} */ every(selector) { const predicate = buildInstPredicate(selector); return this.nodes.every(predicate); } /** * Returns whether or not any of the nodes in the wrapper pass the provided predicate function. * * @param {Function} predicate * @returns {Boolean} */ everyWhere(predicate) { return this.nodes.every((n, i) => predicate.call(this, this.wrap(n), i)); } /** * Utility method used to create new wrappers with a mapping function that returns an array of * nodes in response to a single node wrapper. The returned wrapper is a single wrapper around * all of the mapped nodes flattened (and de-duplicated). * * @param {Function} fn * @returns {ReactWrapper} */ flatMap(fn) { const nodes = this.nodes.map((n, i) => fn.call(this, this.wrap(n), i)); const flattened = flatten(nodes, true); const uniques = unique(flattened); const compacted = compact(uniques); return this.wrap(compacted); } /** * Finds all nodes in the current wrapper nodes' render trees that match the provided predicate * function. * * @param {Function} predicate * @returns {ReactWrapper} */ findWhere(predicate) { return findWhereUnwrapped(this, n => predicate(this.wrap(n))); } /** * Returns the node at a given index of the current wrapper. * * @param {Number} index * @returns {ReactElement} */ get(index) { return this.nodes[index]; } /** * Returns a wrapper around the node at a given index of the current wrapper. * * @param {Number} index * @returns {ReactWrapper} */ at(index) { return this.wrap(this.nodes[index]); } /** * Returns a wrapper around the first node of the current wrapper. * * @returns {ReactWrapper} */ first() { return this.at(0); } /** * Returns a wrapper around the last node of the current wrapper. * * @returns {ReactWrapper} */ last() { return this.at(this.length - 1); } /** * Returns true if the current wrapper has no nodes. False otherwise. * * @returns {boolean} */ isEmpty() { return this.length === 0; } /** * Utility method that throws an error if the current instance has a length other than one. * This is primarily used to enforce that certain methods are only run on a wrapper when it is * wrapping a single node. * * @param {Function} fn * @returns {*} */ single(fn) { if (this.length !== 1) { throw new Error( `This method is only meant to be run on single node. ${this.length} found instead.` ); } return fn.call(this, this.node); } /** * Helpful utility method to create a new wrapper with the same root as the current wrapper, with * any nodes passed in as the first parameter automatically wrapped. * * @param {ReactWrapper|ReactElement|Array<ReactElement>} node * @returns {ReactWrapper} */ wrap(node) { if (node instanceof ReactWrapper) { return node; } return new ReactWrapper(node, this.root); } /** * Returns an HTML-like string of the shallow render for debugging purposes. * * @returns {String} */ debug() { return debugInsts(this.nodes); } /** * Invokes intercepter and returns itself. intercepter is called with itself. * This is helpful when debugging nodes in method chains. * @param fn * @returns {ReactWrapper} */ tap(intercepter) { intercepter(this); return this; } /** * Detaches the react tree from the DOM. Runs `ReactDOM.unmountComponentAtNode()` under the hood. * * This method will most commonly be used as a "cleanup" method if you decide to use the * `attachTo` option in `mount(node, options)`. * * The method is intentionally not "fluent" (in that it doesn't return `this`) because you should * not be doing anything with this wrapper after this method is called. */ detach() { if (this.root !== this) { throw new Error('ReactWrapper::detach() can only be called on the root'); } if (!this.options.attachTo) { throw new Error( 'ReactWrapper::detach() can only be called on when the `attachTo` option was passed into ' + '`mount()`.' ); } unmountComponentAtNode(this.options.attachTo); } }
ui/src/pages/PeopleManagePage/PersonaView.js
LearningLocker/learninglocker
/* eslint-disable react/jsx-indent */ import React from 'react'; import PropTypes from 'prop-types'; import { compose, withProps, setPropTypes, defaultProps } from 'recompose'; import { Map } from 'immutable'; import Tabs from 'ui/components/Material/Tabs'; import { Tab } from 'react-toolbox/lib/tabs'; import { withModel } from 'ui/utils/hocs'; import LabelledInput from 'ui/components/Input/LabelledInput'; import MergeForm from './MergeForm'; import IdentifiersEditor from './IdentifiersEditor'; import AttributesEditor from './AttributesEditor'; const enhance = compose( setPropTypes({ model: PropTypes.instanceOf(Map), }), defaultProps({ model: new Map(), }), withProps(({ model }) => ({ schema: 'persona', id: model.get('_id'), })), withModel ); const render = ({ model, getMetadata, setMetadata, updateModel }) => { const showMergeForm = getMetadata('isMergeFormVisible', false); const activeTab = getMetadata('personaViewActiveTab', 0); const name = model.get('name') || ''; const handleNameChange = (value) => { updateModel({ path: ['name'], value }); }; const handleTabChange = (newActiveTab) => { setMetadata('personaViewActiveTab', newActiveTab); }; if (showMergeForm) { return <MergeForm id={model.get('_id')} />; } return ( <div> <LabelledInput label="Name" value={name} onChange={handleNameChange} /> <Tabs index={activeTab} onChange={handleTabChange}> <Tab label="Identifiers"> <IdentifiersEditor personaId={model.get('_id')} /> </Tab> <Tab label="Attributes"> <AttributesEditor personaId={model.get('_id')} /> </Tab> <Tab label="Merge"> <MergeForm id={model.get('_id')} /> </Tab> </Tabs> </div> ); }; export default enhance(render);
src/routes/register/index.js
Jose4gg/GSW-P2
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Register from './Register'; const title = 'New User Registration'; export default { path: '/register', action() { return { title, component: <Register title={title} />, }; }, };
Step4/app/screens/CounterScreen.js
soulmachine/react-native-starter-kit
// @flow import React, { Component } from 'react'; import Counter from '../components/Counter'; import rootStore from '../store/index'; import { Provider } from 'mobx-react/native'; // provider should receive a single child // <Provider {...stores}> === <Provider store1={stores.store1} store2={stores.store2}> export default class CounterScreen extends Component { render() { return ( <Provider {...rootStore}> <Counter /> </Provider> ); } }
ajax/libs/oojs-ui/0.9.4/oojs-ui.js
sreym/cdnjs
/*! * OOjs UI v0.9.4 * https://www.mediawiki.org/wiki/OOjs_UI * * Copyright 2011–2015 OOjs Team and other contributors. * Released under the MIT license * http://oojs.mit-license.org * * Date: 2015-03-25T22:24:05Z */ ( function ( OO ) { 'use strict'; /** * Namespace for all classes, static methods and static properties. * * @class * @singleton */ OO.ui = {}; OO.ui.bind = $.proxy; /** * @property {Object} */ OO.ui.Keys = { UNDEFINED: 0, BACKSPACE: 8, DELETE: 46, LEFT: 37, RIGHT: 39, UP: 38, DOWN: 40, ENTER: 13, END: 35, HOME: 36, TAB: 9, PAGEUP: 33, PAGEDOWN: 34, ESCAPE: 27, SHIFT: 16, SPACE: 32 }; /** * Get the user's language and any fallback languages. * * These language codes are used to localize user interface elements in the user's language. * * In environments that provide a localization system, this function should be overridden to * return the user's language(s). The default implementation returns English (en) only. * * @return {string[]} Language codes, in descending order of priority */ OO.ui.getUserLanguages = function () { return [ 'en' ]; }; /** * Get a value in an object keyed by language code. * * @param {Object.<string,Mixed>} obj Object keyed by language code * @param {string|null} [lang] Language code, if omitted or null defaults to any user language * @param {string} [fallback] Fallback code, used if no matching language can be found * @return {Mixed} Local value */ OO.ui.getLocalValue = function ( obj, lang, fallback ) { var i, len, langs; // Requested language if ( obj[ lang ] ) { return obj[ lang ]; } // Known user language langs = OO.ui.getUserLanguages(); for ( i = 0, len = langs.length; i < len; i++ ) { lang = langs[ i ]; if ( obj[ lang ] ) { return obj[ lang ]; } } // Fallback language if ( obj[ fallback ] ) { return obj[ fallback ]; } // First existing language for ( lang in obj ) { return obj[ lang ]; } return undefined; }; /** * Check if a node is contained within another node * * Similar to jQuery#contains except a list of containers can be supplied * and a boolean argument allows you to include the container in the match list * * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in * @param {HTMLElement} contained Node to find * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants * @return {boolean} The node is in the list of target nodes */ OO.ui.contains = function ( containers, contained, matchContainers ) { var i; if ( !Array.isArray( containers ) ) { containers = [ containers ]; } for ( i = containers.length - 1; i >= 0; i-- ) { if ( ( matchContainers && contained === containers[ i ] ) || $.contains( containers[ i ], contained ) ) { return true; } } return false; }; /** * Reconstitute a JavaScript object corresponding to a widget created by * the PHP implementation. * * This is an alias for `OO.ui.Element.static.infuse()`. * * @param {string|HTMLElement|jQuery} idOrNode * A DOM id (if a string) or node for the widget to infuse. * @return {OO.ui.Element} * The `OO.ui.Element` corresponding to this (infusable) document node. */ OO.ui.infuse = function ( idOrNode ) { return OO.ui.Element.static.infuse( idOrNode ); }; ( function () { /** * Message store for the default implementation of OO.ui.msg * * Environments that provide a localization system should not use this, but should override * OO.ui.msg altogether. * * @private */ var messages = { // Tool tip for a button that moves items in a list down one place 'ooui-outline-control-move-down': 'Move item down', // Tool tip for a button that moves items in a list up one place 'ooui-outline-control-move-up': 'Move item up', // Tool tip for a button that removes items from a list 'ooui-outline-control-remove': 'Remove item', // Label for the toolbar group that contains a list of all other available tools 'ooui-toolbar-more': 'More', // Label for the fake tool that expands the full list of tools in a toolbar group 'ooui-toolgroup-expand': 'More', // Label for the fake tool that collapses the full list of tools in a toolbar group 'ooui-toolgroup-collapse': 'Fewer', // Default label for the accept button of a confirmation dialog 'ooui-dialog-message-accept': 'OK', // Default label for the reject button of a confirmation dialog 'ooui-dialog-message-reject': 'Cancel', // Title for process dialog error description 'ooui-dialog-process-error': 'Something went wrong', // Label for process dialog dismiss error button, visible when describing errors 'ooui-dialog-process-dismiss': 'Dismiss', // Label for process dialog retry action button, visible when describing only recoverable errors 'ooui-dialog-process-retry': 'Try again', // Label for process dialog retry action button, visible when describing only warnings 'ooui-dialog-process-continue': 'Continue' }; /** * Get a localized message. * * In environments that provide a localization system, this function should be overridden to * return the message translated in the user's language. The default implementation always returns * English messages. * * After the message key, message parameters may optionally be passed. In the default implementation, * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc. * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as * they support unnamed, ordered message parameters. * * @abstract * @param {string} key Message key * @param {Mixed...} [params] Message parameters * @return {string} Translated message with parameters substituted */ OO.ui.msg = function ( key ) { var message = messages[ key ], params = Array.prototype.slice.call( arguments, 1 ); if ( typeof message === 'string' ) { // Perform $1 substitution message = message.replace( /\$(\d+)/g, function ( unused, n ) { var i = parseInt( n, 10 ); return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n; } ); } else { // Return placeholder if message not found message = '[' + key + ']'; } return message; }; /** * Package a message and arguments for deferred resolution. * * Use this when you are statically specifying a message and the message may not yet be present. * * @param {string} key Message key * @param {Mixed...} [params] Message parameters * @return {Function} Function that returns the resolved message when executed */ OO.ui.deferMsg = function () { var args = arguments; return function () { return OO.ui.msg.apply( OO.ui, args ); }; }; /** * Resolve a message. * * If the message is a function it will be executed, otherwise it will pass through directly. * * @param {Function|string} msg Deferred message, or message text * @return {string} Resolved message */ OO.ui.resolveMsg = function ( msg ) { if ( $.isFunction( msg ) ) { return msg(); } return msg; }; } )(); /** * Element that can be marked as pending. * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element */ OO.ui.PendingElement = function OoUiPendingElement( config ) { // Configuration initialization config = config || {}; // Properties this.pending = 0; this.$pending = null; // Initialisation this.setPendingElement( config.$pending || this.$element ); }; /* Setup */ OO.initClass( OO.ui.PendingElement ); /* Methods */ /** * Set the pending element (and clean up any existing one). * * @param {jQuery} $pending The element to set to pending. */ OO.ui.PendingElement.prototype.setPendingElement = function ( $pending ) { if ( this.$pending ) { this.$pending.removeClass( 'oo-ui-pendingElement-pending' ); } this.$pending = $pending; if ( this.pending > 0 ) { this.$pending.addClass( 'oo-ui-pendingElement-pending' ); } }; /** * Check if input is pending. * * @return {boolean} */ OO.ui.PendingElement.prototype.isPending = function () { return !!this.pending; }; /** * Increase the pending stack. * * @chainable */ OO.ui.PendingElement.prototype.pushPending = function () { if ( this.pending === 0 ) { this.$pending.addClass( 'oo-ui-pendingElement-pending' ); this.updateThemeClasses(); } this.pending++; return this; }; /** * Reduce the pending stack. * * Clamped at zero. * * @chainable */ OO.ui.PendingElement.prototype.popPending = function () { if ( this.pending === 1 ) { this.$pending.removeClass( 'oo-ui-pendingElement-pending' ); this.updateThemeClasses(); } this.pending = Math.max( 0, this.pending - 1 ); return this; }; /** * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them. * Actions can be made available for specific contexts (modes) and circumstances * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}. * * ActionSets contain two types of actions: * * - Special: Special actions are the first visible actions with special flags, such as 'safe' and 'primary', the default special flags. Additional special flags can be configured in subclasses with the static #specialFlags property. * - Other: Other actions include all non-special visible actions. * * Please see the [OOjs UI documentation on MediaWiki][1] for more information. * * @example * // Example: An action set used in a process dialog * function MyProcessDialog( config ) { * MyProcessDialog.super.call( this, config ); * } * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog ); * MyProcessDialog.static.title = 'An action set in a process dialog'; * // An action set that uses modes ('edit' and 'help' mode, in this example). * MyProcessDialog.static.actions = [ * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] }, * { action: 'help', modes: 'edit', label: 'Help' }, * { modes: 'edit', label: 'Cancel', flags: 'safe' }, * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' } * ]; * * MyProcessDialog.prototype.initialize = function () { * MyProcessDialog.super.prototype.initialize.apply( this, arguments ); * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } ); * this.panel1.$element.append( '<p>This dialog uses an action set (continue, help, cancel, back) configured with modes. This is edit mode. Click \'help\' to see help mode.</p>' ); * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } ); * this.panel2.$element.append( '<p>This is help mode. Only the \'back\' action widget is configured to be visible here. Click \'back\' to return to \'edit\' mode.</p>' ); * this.stackLayout = new OO.ui.StackLayout( { * items: [ this.panel1, this.panel2 ] * } ); * this.$body.append( this.stackLayout.$element ); * }; * MyProcessDialog.prototype.getSetupProcess = function ( data ) { * return MyProcessDialog.super.prototype.getSetupProcess.call( this, data ) * .next( function () { * this.actions.setMode( 'edit' ); * }, this ); * }; * MyProcessDialog.prototype.getActionProcess = function ( action ) { * if ( action === 'help' ) { * this.actions.setMode( 'help' ); * this.stackLayout.setItem( this.panel2 ); * } else if ( action === 'back' ) { * this.actions.setMode( 'edit' ); * this.stackLayout.setItem( this.panel1 ); * } else if ( action === 'continue' ) { * var dialog = this; * return new OO.ui.Process( function () { * dialog.close(); * } ); * } * return MyProcessDialog.super.prototype.getActionProcess.call( this, action ); * }; * MyProcessDialog.prototype.getBodyHeight = function () { * return this.panel1.$element.outerHeight( true ); * }; * var windowManager = new OO.ui.WindowManager(); * $( 'body' ).append( windowManager.$element ); * var dialog = new MyProcessDialog( { * size: 'medium' * } ); * windowManager.addWindows( [ dialog ] ); * windowManager.openWindow( dialog ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets * * @abstract * @class * @mixins OO.EventEmitter * * @constructor * @param {Object} [config] Configuration options */ OO.ui.ActionSet = function OoUiActionSet( config ) { // Configuration initialization config = config || {}; // Mixin constructors OO.EventEmitter.call( this ); // Properties this.list = []; this.categories = { actions: 'getAction', flags: 'getFlags', modes: 'getModes' }; this.categorized = {}; this.special = {}; this.others = []; this.organized = false; this.changing = false; this.changed = false; }; /* Setup */ OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter ); /* Static Properties */ /** * Symbolic name of the flags used to identify special actions. Special actions are displayed in the * header of a {@link OO.ui.ProcessDialog process dialog}. * See the [OOjs UI documentation on MediaWiki][2] for more information and examples. * * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs * * @abstract * @static * @inheritable * @property {string} */ OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ]; /* Events */ /** * @event click * * A 'click' event is emitted when an action is clicked. * * @param {OO.ui.ActionWidget} action Action that was clicked */ /** * @event resize * * A 'resize' event is emitted when an action widget is resized. * * @param {OO.ui.ActionWidget} action Action that was resized */ /** * @event add * * An 'add' event is emitted when actions are {@link #method-add added} to the action set. * * @param {OO.ui.ActionWidget[]} added Actions added */ /** * @event remove * * A 'remove' event is emitted when actions are {@link #method-remove removed} * or {@link #clear cleared}. * * @param {OO.ui.ActionWidget[]} added Actions removed */ /** * @event change * * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared}, * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed. * */ /* Methods */ /** * Handle action change events. * * @private * @fires change */ OO.ui.ActionSet.prototype.onActionChange = function () { this.organized = false; if ( this.changing ) { this.changed = true; } else { this.emit( 'change' ); } }; /** * Check if an action is one of the special actions. * * @param {OO.ui.ActionWidget} action Action to check * @return {boolean} Action is special */ OO.ui.ActionSet.prototype.isSpecial = function ( action ) { var flag; for ( flag in this.special ) { if ( action === this.special[ flag ] ) { return true; } } return false; }; /** * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’, * or ‘disabled’. * * @param {Object} [filters] Filters to use, omit to get all actions * @param {string|string[]} [filters.actions] Actions that action widgets must have * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe') * @param {string|string[]} [filters.modes] Modes that action widgets must have * @param {boolean} [filters.visible] Action widgets must be visible * @param {boolean} [filters.disabled] Action widgets must be disabled * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria */ OO.ui.ActionSet.prototype.get = function ( filters ) { var i, len, list, category, actions, index, match, matches; if ( filters ) { this.organize(); // Collect category candidates matches = []; for ( category in this.categorized ) { list = filters[ category ]; if ( list ) { if ( !Array.isArray( list ) ) { list = [ list ]; } for ( i = 0, len = list.length; i < len; i++ ) { actions = this.categorized[ category ][ list[ i ] ]; if ( Array.isArray( actions ) ) { matches.push.apply( matches, actions ); } } } } // Remove by boolean filters for ( i = 0, len = matches.length; i < len; i++ ) { match = matches[ i ]; if ( ( filters.visible !== undefined && match.isVisible() !== filters.visible ) || ( filters.disabled !== undefined && match.isDisabled() !== filters.disabled ) ) { matches.splice( i, 1 ); len--; i--; } } // Remove duplicates for ( i = 0, len = matches.length; i < len; i++ ) { match = matches[ i ]; index = matches.lastIndexOf( match ); while ( index !== i ) { matches.splice( index, 1 ); len--; index = matches.lastIndexOf( match ); } } return matches; } return this.list.slice(); }; /** * Get 'special' actions. * * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'. * Special flags can be configured in subclasses by changing the static #specialFlags property. * * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets. */ OO.ui.ActionSet.prototype.getSpecial = function () { this.organize(); return $.extend( {}, this.special ); }; /** * Get 'other' actions. * * Other actions include all non-special visible action widgets. * * @return {OO.ui.ActionWidget[]} 'Other' action widgets */ OO.ui.ActionSet.prototype.getOthers = function () { this.organize(); return this.others.slice(); }; /** * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured * to be available in the specified mode will be made visible. All other actions will be hidden. * * @param {string} mode The mode. Only actions configured to be available in the specified * mode will be made visible. * @chainable * @fires toggle * @fires change */ OO.ui.ActionSet.prototype.setMode = function ( mode ) { var i, len, action; this.changing = true; for ( i = 0, len = this.list.length; i < len; i++ ) { action = this.list[ i ]; action.toggle( action.hasMode( mode ) ); } this.organized = false; this.changing = false; this.emit( 'change' ); return this; }; /** * Set the abilities of the specified actions. * * Action widgets that are configured with the specified actions will be enabled * or disabled based on the boolean values specified in the `actions` * parameter. * * @param {Object.<string,boolean>} actions A list keyed by action name with boolean * values that indicate whether or not the action should be enabled. * @chainable */ OO.ui.ActionSet.prototype.setAbilities = function ( actions ) { var i, len, action, item; for ( i = 0, len = this.list.length; i < len; i++ ) { item = this.list[ i ]; action = item.getAction(); if ( actions[ action ] !== undefined ) { item.setDisabled( !actions[ action ] ); } } return this; }; /** * Executes a function once per action. * * When making changes to multiple actions, use this method instead of iterating over the actions * manually to defer emitting a #change event until after all actions have been changed. * * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get * @param {Function} callback Callback to run for each action; callback is invoked with three * arguments: the action, the action's index, the list of actions being iterated over * @chainable */ OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) { this.changed = false; this.changing = true; this.get( filter ).forEach( callback ); this.changing = false; if ( this.changed ) { this.emit( 'change' ); } return this; }; /** * Add action widgets to the action set. * * @param {OO.ui.ActionWidget[]} actions Action widgets to add * @chainable * @fires add * @fires change */ OO.ui.ActionSet.prototype.add = function ( actions ) { var i, len, action; this.changing = true; for ( i = 0, len = actions.length; i < len; i++ ) { action = actions[ i ]; action.connect( this, { click: [ 'emit', 'click', action ], resize: [ 'emit', 'resize', action ], toggle: [ 'onActionChange' ] } ); this.list.push( action ); } this.organized = false; this.emit( 'add', actions ); this.changing = false; this.emit( 'change' ); return this; }; /** * Remove action widgets from the set. * * To remove all actions, you may wish to use the #clear method instead. * * @param {OO.ui.ActionWidget[]} actions Action widgets to remove * @chainable * @fires remove * @fires change */ OO.ui.ActionSet.prototype.remove = function ( actions ) { var i, len, index, action; this.changing = true; for ( i = 0, len = actions.length; i < len; i++ ) { action = actions[ i ]; index = this.list.indexOf( action ); if ( index !== -1 ) { action.disconnect( this ); this.list.splice( index, 1 ); } } this.organized = false; this.emit( 'remove', actions ); this.changing = false; this.emit( 'change' ); return this; }; /** * Remove all action widets from the set. * * To remove only specified actions, use the {@link #method-remove remove} method instead. * * @chainable * @fires remove * @fires change */ OO.ui.ActionSet.prototype.clear = function () { var i, len, action, removed = this.list.slice(); this.changing = true; for ( i = 0, len = this.list.length; i < len; i++ ) { action = this.list[ i ]; action.disconnect( this ); } this.list = []; this.organized = false; this.emit( 'remove', removed ); this.changing = false; this.emit( 'change' ); return this; }; /** * Organize actions. * * This is called whenever organized information is requested. It will only reorganize the actions * if something has changed since the last time it ran. * * @private * @chainable */ OO.ui.ActionSet.prototype.organize = function () { var i, iLen, j, jLen, flag, action, category, list, item, special, specialFlags = this.constructor.static.specialFlags; if ( !this.organized ) { this.categorized = {}; this.special = {}; this.others = []; for ( i = 0, iLen = this.list.length; i < iLen; i++ ) { action = this.list[ i ]; if ( action.isVisible() ) { // Populate categories for ( category in this.categories ) { if ( !this.categorized[ category ] ) { this.categorized[ category ] = {}; } list = action[ this.categories[ category ] ](); if ( !Array.isArray( list ) ) { list = [ list ]; } for ( j = 0, jLen = list.length; j < jLen; j++ ) { item = list[ j ]; if ( !this.categorized[ category ][ item ] ) { this.categorized[ category ][ item ] = []; } this.categorized[ category ][ item ].push( action ); } } // Populate special/others special = false; for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) { flag = specialFlags[ j ]; if ( !this.special[ flag ] && action.hasFlag( flag ) ) { this.special[ flag ] = action; special = true; break; } } if ( !special ) { this.others.push( action ); } } } this.organized = true; } return this; }; /** * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events * connected to them and can't be interacted with. * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2] * for an example. * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample * @cfg {string} [id] The HTML id attribute used in the rendered tag. * @cfg {string} [text] Text to insert * @cfg {Array} [content] An array of content elements to append (after #text). * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML. * Instances of OO.ui.Element will have their $element appended. * @cfg {jQuery} [$content] Content elements to append (after #text) * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object). * Data can also be specified with the #setData method. */ OO.ui.Element = function OoUiElement( config ) { // Configuration initialization config = config || {}; // Properties this.$ = $; this.visible = true; this.data = config.data; this.$element = config.$element || $( document.createElement( this.getTagName() ) ); this.elementGroup = null; this.debouncedUpdateThemeClassesHandler = this.debouncedUpdateThemeClasses.bind( this ); this.updateThemeClassesPending = false; // Initialization if ( Array.isArray( config.classes ) ) { this.$element.addClass( config.classes.join( ' ' ) ); } if ( config.id ) { this.$element.attr( 'id', config.id ); } if ( config.text ) { this.$element.text( config.text ); } if ( config.content ) { // The `content` property treats plain strings as text; use an // HtmlSnippet to append HTML content. `OO.ui.Element`s get their // appropriate $element appended. this.$element.append( config.content.map( function ( v ) { if ( typeof v === 'string' ) { // Escape string so it is properly represented in HTML. return document.createTextNode( v ); } else if ( v instanceof OO.ui.HtmlSnippet ) { // Bypass escaping. return v.toString(); } else if ( v instanceof OO.ui.Element ) { return v.$element; } return v; } ) ); } if ( config.$content ) { // The `$content` property treats plain strings as HTML. this.$element.append( config.$content ); } }; /* Setup */ OO.initClass( OO.ui.Element ); /* Static Properties */ /** * The name of the HTML tag used by the element. * * The static value may be ignored if the #getTagName method is overridden. * * @static * @inheritable * @property {string} */ OO.ui.Element.static.tagName = 'div'; /* Static Methods */ /** * Reconstitute a JavaScript object corresponding to a widget created * by the PHP implementation. * * @param {string|HTMLElement|jQuery} idOrNode * A DOM id (if a string) or node for the widget to infuse. * @return {OO.ui.Element} * The `OO.ui.Element` corresponding to this (infusable) document node. * For `Tag` objects emitted on the HTML side (used occasionally for content) * the value returned is a newly-created Element wrapping around the existing * DOM node. */ OO.ui.Element.static.infuse = function ( idOrNode ) { var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, true ); // Verify that the type matches up. // FIXME: uncomment after T89721 is fixed (see T90929) /* if ( !( obj instanceof this['class'] ) ) { throw new Error( 'Infusion type mismatch!' ); } */ return obj; }; /** * Implementation helper for `infuse`; skips the type check and has an * extra property so that only the top-level invocation touches the DOM. * @private * @param {string|HTMLElement|jQuery} idOrNode * @param {boolean} top True only for top-level invocation. * @return {OO.ui.Element} */ OO.ui.Element.static.unsafeInfuse = function ( idOrNode, top ) { // look for a cached result of a previous infusion. var id, $elem, data, cls, obj; if ( typeof idOrNode === 'string' ) { id = idOrNode; $elem = $( document.getElementById( id ) ); } else { $elem = $( idOrNode ); id = $elem.attr( 'id' ); } data = $elem.data( 'ooui-infused' ); if ( data ) { // cached! if ( data === true ) { throw new Error( 'Circular dependency! ' + id ); } return data; } if ( !$elem.length ) { throw new Error( 'Widget not found: ' + id ); } data = $elem.attr( 'data-ooui' ); if ( !data ) { throw new Error( 'No infusion data found: ' + id ); } try { data = $.parseJSON( data ); } catch ( _ ) { data = null; } if ( !( data && data._ ) ) { throw new Error( 'No valid infusion data found: ' + id ); } if ( data._ === 'Tag' ) { // Special case: this is a raw Tag; wrap existing node, don't rebuild. return new OO.ui.Element( { $element: $elem } ); } cls = OO.ui[data._]; if ( !cls ) { throw new Error( 'Unknown widget type: ' + id ); } $elem.data( 'ooui-infused', true ); // prevent loops data.id = id; // implicit data = OO.copy( data, null, function deserialize( value ) { if ( OO.isPlainObject( value ) ) { if ( value.tag ) { return OO.ui.Element.static.unsafeInfuse( value.tag, false ); } if ( value.html ) { return new OO.ui.HtmlSnippet( value.html ); } } } ); // jscs:disable requireCapitalizedConstructors obj = new cls( data ); // rebuild widget // now replace old DOM with this new DOM. if ( top ) { $elem.replaceWith( obj.$element ); } obj.$element.data( 'ooui-infused', obj ); // set the 'data-ooui' attribute so we can identify infused widgets obj.$element.attr( 'data-ooui', '' ); return obj; }; /** * Get a jQuery function within a specific document. * * @static * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is * not in an iframe * @return {Function} Bound jQuery function */ OO.ui.Element.static.getJQuery = function ( context, $iframe ) { function wrapper( selector ) { return $( selector, wrapper.context ); } wrapper.context = this.getDocument( context ); if ( $iframe ) { wrapper.$iframe = $iframe; } return wrapper; }; /** * Get the document of an element. * * @static * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for * @return {HTMLDocument|null} Document object */ OO.ui.Element.static.getDocument = function ( obj ) { // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) || // Empty jQuery selections might have a context obj.context || // HTMLElement obj.ownerDocument || // Window obj.document || // HTMLDocument ( obj.nodeType === 9 && obj ) || null; }; /** * Get the window of an element or document. * * @static * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for * @return {Window} Window object */ OO.ui.Element.static.getWindow = function ( obj ) { var doc = this.getDocument( obj ); return doc.parentWindow || doc.defaultView; }; /** * Get the direction of an element or document. * * @static * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for * @return {string} Text direction, either 'ltr' or 'rtl' */ OO.ui.Element.static.getDir = function ( obj ) { var isDoc, isWin; if ( obj instanceof jQuery ) { obj = obj[ 0 ]; } isDoc = obj.nodeType === 9; isWin = obj.document !== undefined; if ( isDoc || isWin ) { if ( isWin ) { obj = obj.document; } obj = obj.body; } return $( obj ).css( 'direction' ); }; /** * Get the offset between two frames. * * TODO: Make this function not use recursion. * * @static * @param {Window} from Window of the child frame * @param {Window} [to=window] Window of the parent frame * @param {Object} [offset] Offset to start with, used internally * @return {Object} Offset object, containing left and top properties */ OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) { var i, len, frames, frame, rect; if ( !to ) { to = window; } if ( !offset ) { offset = { top: 0, left: 0 }; } if ( from.parent === from ) { return offset; } // Get iframe element frames = from.parent.document.getElementsByTagName( 'iframe' ); for ( i = 0, len = frames.length; i < len; i++ ) { if ( frames[ i ].contentWindow === from ) { frame = frames[ i ]; break; } } // Recursively accumulate offset values if ( frame ) { rect = frame.getBoundingClientRect(); offset.left += rect.left; offset.top += rect.top; if ( from !== to ) { this.getFrameOffset( from.parent, offset ); } } return offset; }; /** * Get the offset between two elements. * * The two elements may be in a different frame, but in that case the frame $element is in must * be contained in the frame $anchor is in. * * @static * @param {jQuery} $element Element whose position to get * @param {jQuery} $anchor Element to get $element's position relative to * @return {Object} Translated position coordinates, containing top and left properties */ OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) { var iframe, iframePos, pos = $element.offset(), anchorPos = $anchor.offset(), elementDocument = this.getDocument( $element ), anchorDocument = this.getDocument( $anchor ); // If $element isn't in the same document as $anchor, traverse up while ( elementDocument !== anchorDocument ) { iframe = elementDocument.defaultView.frameElement; if ( !iframe ) { throw new Error( '$element frame is not contained in $anchor frame' ); } iframePos = $( iframe ).offset(); pos.left += iframePos.left; pos.top += iframePos.top; elementDocument = iframe.ownerDocument; } pos.left -= anchorPos.left; pos.top -= anchorPos.top; return pos; }; /** * Get element border sizes. * * @static * @param {HTMLElement} el Element to measure * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties */ OO.ui.Element.static.getBorders = function ( el ) { var doc = el.ownerDocument, win = doc.parentWindow || doc.defaultView, style = win && win.getComputedStyle ? win.getComputedStyle( el, null ) : el.currentStyle, $el = $( el ), top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0, left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0, bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0, right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0; return { top: top, left: left, bottom: bottom, right: right }; }; /** * Get dimensions of an element or window. * * @static * @param {HTMLElement|Window} el Element to measure * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties */ OO.ui.Element.static.getDimensions = function ( el ) { var $el, $win, doc = el.ownerDocument || el.document, win = doc.parentWindow || doc.defaultView; if ( win === el || el === doc.documentElement ) { $win = $( win ); return { borders: { top: 0, left: 0, bottom: 0, right: 0 }, scroll: { top: $win.scrollTop(), left: $win.scrollLeft() }, scrollbar: { right: 0, bottom: 0 }, rect: { top: 0, left: 0, bottom: $win.innerHeight(), right: $win.innerWidth() } }; } else { $el = $( el ); return { borders: this.getBorders( el ), scroll: { top: $el.scrollTop(), left: $el.scrollLeft() }, scrollbar: { right: $el.innerWidth() - el.clientWidth, bottom: $el.innerHeight() - el.clientHeight }, rect: el.getBoundingClientRect() }; } }; /** * Get scrollable object parent * * documentElement can't be used to get or set the scrollTop * property on Blink. Changing and testing its value lets us * use 'body' or 'documentElement' based on what is working. * * https://code.google.com/p/chromium/issues/detail?id=303131 * * @static * @param {HTMLElement} el Element to find scrollable parent for * @return {HTMLElement} Scrollable parent */ OO.ui.Element.static.getRootScrollableElement = function ( el ) { var scrollTop, body; if ( OO.ui.scrollableElement === undefined ) { body = el.ownerDocument.body; scrollTop = body.scrollTop; body.scrollTop = 1; if ( body.scrollTop === 1 ) { body.scrollTop = scrollTop; OO.ui.scrollableElement = 'body'; } else { OO.ui.scrollableElement = 'documentElement'; } } return el.ownerDocument[ OO.ui.scrollableElement ]; }; /** * Get closest scrollable container. * * Traverses up until either a scrollable element or the root is reached, in which case the window * will be returned. * * @static * @param {HTMLElement} el Element to find scrollable container for * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either * @return {HTMLElement} Closest scrollable container */ OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) { var i, val, props = [ 'overflow' ], $parent = $( el ).parent(); if ( dimension === 'x' || dimension === 'y' ) { props.push( 'overflow-' + dimension ); } while ( $parent.length ) { if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) { return $parent[ 0 ]; } i = props.length; while ( i-- ) { val = $parent.css( props[ i ] ); if ( val === 'auto' || val === 'scroll' ) { return $parent[ 0 ]; } } $parent = $parent.parent(); } return this.getDocument( el ).body; }; /** * Scroll element into view. * * @static * @param {HTMLElement} el Element to scroll into view * @param {Object} [config] Configuration options * @param {string} [config.duration] jQuery animation duration value * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit * to scroll in both directions * @param {Function} [config.complete] Function to call when scrolling completes */ OO.ui.Element.static.scrollIntoView = function ( el, config ) { // Configuration initialization config = config || {}; var rel, anim = {}, callback = typeof config.complete === 'function' && config.complete, sc = this.getClosestScrollableContainer( el, config.direction ), $sc = $( sc ), eld = this.getDimensions( el ), scd = this.getDimensions( sc ), $win = $( this.getWindow( el ) ); // Compute the distances between the edges of el and the edges of the scroll viewport if ( $sc.is( 'html, body' ) ) { // If the scrollable container is the root, this is easy rel = { top: eld.rect.top, bottom: $win.innerHeight() - eld.rect.bottom, left: eld.rect.left, right: $win.innerWidth() - eld.rect.right }; } else { // Otherwise, we have to subtract el's coordinates from sc's coordinates rel = { top: eld.rect.top - ( scd.rect.top + scd.borders.top ), bottom: scd.rect.bottom - scd.borders.bottom - scd.scrollbar.bottom - eld.rect.bottom, left: eld.rect.left - ( scd.rect.left + scd.borders.left ), right: scd.rect.right - scd.borders.right - scd.scrollbar.right - eld.rect.right }; } if ( !config.direction || config.direction === 'y' ) { if ( rel.top < 0 ) { anim.scrollTop = scd.scroll.top + rel.top; } else if ( rel.top > 0 && rel.bottom < 0 ) { anim.scrollTop = scd.scroll.top + Math.min( rel.top, -rel.bottom ); } } if ( !config.direction || config.direction === 'x' ) { if ( rel.left < 0 ) { anim.scrollLeft = scd.scroll.left + rel.left; } else if ( rel.left > 0 && rel.right < 0 ) { anim.scrollLeft = scd.scroll.left + Math.min( rel.left, -rel.right ); } } if ( !$.isEmptyObject( anim ) ) { $sc.stop( true ).animate( anim, config.duration || 'fast' ); if ( callback ) { $sc.queue( function ( next ) { callback(); next(); } ); } } else { if ( callback ) { callback(); } } }; /** * Force the browser to reconsider whether it really needs to render scrollbars inside the element * and reserve space for them, because it probably doesn't. * * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow, * and then reattach (or show) them back. * * @static * @param {HTMLElement} el Element to reconsider the scrollbars on */ OO.ui.Element.static.reconsiderScrollbars = function ( el ) { var i, len, nodes = []; // Detach all children while ( el.firstChild ) { nodes.push( el.firstChild ); el.removeChild( el.firstChild ); } // Force reflow void el.offsetHeight; // Reattach all children for ( i = 0, len = nodes.length; i < len; i++ ) { el.appendChild( nodes[ i ] ); } }; /* Methods */ /** * Toggle visibility of an element. * * @param {boolean} [show] Make element visible, omit to toggle visibility * @fires visible * @chainable */ OO.ui.Element.prototype.toggle = function ( show ) { show = show === undefined ? !this.visible : !!show; if ( show !== this.isVisible() ) { this.visible = show; this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible ); this.emit( 'toggle', show ); } return this; }; /** * Check if element is visible. * * @return {boolean} element is visible */ OO.ui.Element.prototype.isVisible = function () { return this.visible; }; /** * Get element data. * * @return {Mixed} Element data */ OO.ui.Element.prototype.getData = function () { return this.data; }; /** * Set element data. * * @param {Mixed} Element data * @chainable */ OO.ui.Element.prototype.setData = function ( data ) { this.data = data; return this; }; /** * Check if element supports one or more methods. * * @param {string|string[]} methods Method or list of methods to check * @return {boolean} All methods are supported */ OO.ui.Element.prototype.supports = function ( methods ) { var i, len, support = 0; methods = Array.isArray( methods ) ? methods : [ methods ]; for ( i = 0, len = methods.length; i < len; i++ ) { if ( $.isFunction( this[ methods[ i ] ] ) ) { support++; } } return methods.length === support; }; /** * Update the theme-provided classes. * * @localdoc This is called in element mixins and widget classes any time state changes. * Updating is debounced, minimizing overhead of changing multiple attributes and * guaranteeing that theme updates do not occur within an element's constructor */ OO.ui.Element.prototype.updateThemeClasses = function () { if ( !this.updateThemeClassesPending ) { this.updateThemeClassesPending = true; setTimeout( this.debouncedUpdateThemeClassesHandler ); } }; /** * @private */ OO.ui.Element.prototype.debouncedUpdateThemeClasses = function () { OO.ui.theme.updateElementClasses( this ); this.updateThemeClassesPending = false; }; /** * Get the HTML tag name. * * Override this method to base the result on instance information. * * @return {string} HTML tag name */ OO.ui.Element.prototype.getTagName = function () { return this.constructor.static.tagName; }; /** * Check if the element is attached to the DOM * @return {boolean} The element is attached to the DOM */ OO.ui.Element.prototype.isElementAttached = function () { return $.contains( this.getElementDocument(), this.$element[ 0 ] ); }; /** * Get the DOM document. * * @return {HTMLDocument} Document object */ OO.ui.Element.prototype.getElementDocument = function () { // Don't cache this in other ways either because subclasses could can change this.$element return OO.ui.Element.static.getDocument( this.$element ); }; /** * Get the DOM window. * * @return {Window} Window object */ OO.ui.Element.prototype.getElementWindow = function () { return OO.ui.Element.static.getWindow( this.$element ); }; /** * Get closest scrollable container. */ OO.ui.Element.prototype.getClosestScrollableElementContainer = function () { return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] ); }; /** * Get group element is in. * * @return {OO.ui.GroupElement|null} Group element, null if none */ OO.ui.Element.prototype.getElementGroup = function () { return this.elementGroup; }; /** * Set group element is in. * * @param {OO.ui.GroupElement|null} group Group element, null if none * @chainable */ OO.ui.Element.prototype.setElementGroup = function ( group ) { this.elementGroup = group; return this; }; /** * Scroll element into view. * * @param {Object} [config] Configuration options */ OO.ui.Element.prototype.scrollElementIntoView = function ( config ) { return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config ); }; /** * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined. * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout}, * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout}, * and {@link OO.ui.BookletLayout BookletLayout} for more information and examples. * * @abstract * @class * @extends OO.ui.Element * @mixins OO.EventEmitter * * @constructor * @param {Object} [config] Configuration options */ OO.ui.Layout = function OoUiLayout( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.Layout.super.call( this, config ); // Mixin constructors OO.EventEmitter.call( this ); // Initialization this.$element.addClass( 'oo-ui-layout' ); }; /* Setup */ OO.inheritClass( OO.ui.Layout, OO.ui.Element ); OO.mixinClass( OO.ui.Layout, OO.EventEmitter ); /** * Widgets are compositions of one or more OOjs UI elements that users can both view * and interact with. All widgets can be configured and modified via a standard API, * and their state can change dynamically according to a model. * * @abstract * @class * @extends OO.ui.Element * @mixins OO.EventEmitter * * @constructor * @param {Object} [config] Configuration options * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their * appearance reflects this state. */ OO.ui.Widget = function OoUiWidget( config ) { // Initialize config config = $.extend( { disabled: false }, config ); // Parent constructor OO.ui.Widget.super.call( this, config ); // Mixin constructors OO.EventEmitter.call( this ); // Properties this.disabled = null; this.wasDisabled = null; // Initialization this.$element.addClass( 'oo-ui-widget' ); this.setDisabled( !!config.disabled ); }; /* Setup */ OO.inheritClass( OO.ui.Widget, OO.ui.Element ); OO.mixinClass( OO.ui.Widget, OO.EventEmitter ); /* Events */ /** * @event disable * * A 'disable' event is emitted when a widget is disabled. * * @param {boolean} disabled Widget is disabled */ /** * @event toggle * * A 'toggle' event is emitted when the visibility of the widget changes. * * @param {boolean} visible Widget is visible */ /* Methods */ /** * Check if the widget is disabled. * * @return {boolean} Widget is disabled */ OO.ui.Widget.prototype.isDisabled = function () { return this.disabled; }; /** * Set the 'disabled' state of the widget. * * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state. * * @param {boolean} disabled Disable widget * @chainable */ OO.ui.Widget.prototype.setDisabled = function ( disabled ) { var isDisabled; this.disabled = !!disabled; isDisabled = this.isDisabled(); if ( isDisabled !== this.wasDisabled ) { this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled ); this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled ); this.$element.attr( 'aria-disabled', isDisabled.toString() ); this.emit( 'disable', isDisabled ); this.updateThemeClasses(); } this.wasDisabled = isDisabled; return this; }; /** * Update the disabled state, in case of changes in parent widget. * * @chainable */ OO.ui.Widget.prototype.updateDisabled = function () { this.setDisabled( this.disabled ); return this; }; /** * A window is a container for elements that are in a child frame. They are used with * a window manager (OO.ui.WindowManager), which is used to open and close the window and control * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’, * ‘large’), which is interpreted by the window manager. If the requested size is not recognized, * the window manager will choose a sensible fallback. * * The lifecycle of a window has three primary stages (opening, opened, and closing) in which * different processes are executed: * * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open * the window. * * - {@link #getSetupProcess} method is called and its result executed * - {@link #getReadyProcess} method is called and its result executed * * **opened**: The window is now open * * **closing**: The closing stage begins when the window manager's * {@link OO.ui.WindowManager#closeWindow closeWindow} * or the window's {@link #close} methods are used, and the window manager begins to close the window. * * - {@link #getHoldProcess} method is called and its result executed * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed * * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous * processing can complete. Always assume window processes are executed asynchronously. * * For more information, please see the [OOjs UI documentation on MediaWiki] [1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows * * @abstract * @class * @extends OO.ui.Element * @mixins OO.EventEmitter * * @constructor * @param {Object} [config] Configuration options * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or * `full`. If omitted, the value of the {@link #static-size static size} property will be used. */ OO.ui.Window = function OoUiWindow( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.Window.super.call( this, config ); // Mixin constructors OO.EventEmitter.call( this ); // Properties this.manager = null; this.size = config.size || this.constructor.static.size; this.$frame = $( '<div>' ); this.$overlay = $( '<div>' ); this.$content = $( '<div>' ); // Initialization this.$overlay.addClass( 'oo-ui-window-overlay' ); this.$content .addClass( 'oo-ui-window-content' ) .attr( 'tabIndex', 0 ); this.$frame .addClass( 'oo-ui-window-frame' ) .append( this.$content ); this.$element .addClass( 'oo-ui-window' ) .append( this.$frame, this.$overlay ); // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods // that reference properties not initialized at that time of parent class construction // TODO: Find a better way to handle post-constructor setup this.visible = false; this.$element.addClass( 'oo-ui-element-hidden' ); }; /* Setup */ OO.inheritClass( OO.ui.Window, OO.ui.Element ); OO.mixinClass( OO.ui.Window, OO.EventEmitter ); /* Static Properties */ /** * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`. * * The static size is used if no #size is configured during construction. * * @static * @inheritable * @property {string} */ OO.ui.Window.static.size = 'medium'; /* Methods */ /** * Handle mouse down events. * * @private * @param {jQuery.Event} e Mouse down event */ OO.ui.Window.prototype.onMouseDown = function ( e ) { // Prevent clicking on the click-block from stealing focus if ( e.target === this.$element[ 0 ] ) { return false; } }; /** * Check if the window has been initialized. * * Initialization occurs when a window is added to a manager. * * @return {boolean} Window has been initialized */ OO.ui.Window.prototype.isInitialized = function () { return !!this.manager; }; /** * Check if the window is visible. * * @return {boolean} Window is visible */ OO.ui.Window.prototype.isVisible = function () { return this.visible; }; /** * Check if the window is opening. * * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening} * method. * * @return {boolean} Window is opening */ OO.ui.Window.prototype.isOpening = function () { return this.manager.isOpening( this ); }; /** * Check if the window is closing. * * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method. * * @return {boolean} Window is closing */ OO.ui.Window.prototype.isClosing = function () { return this.manager.isClosing( this ); }; /** * Check if the window is opened. * * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method. * * @return {boolean} Window is opened */ OO.ui.Window.prototype.isOpened = function () { return this.manager.isOpened( this ); }; /** * Get the window manager. * * All windows must be attached to a window manager, which is used to open * and close the window and control its presentation. * * @return {OO.ui.WindowManager} Manager of window */ OO.ui.Window.prototype.getManager = function () { return this.manager; }; /** * Get the symbolic name of the window size (e.g., `small` or `medium`). * * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full` */ OO.ui.Window.prototype.getSize = function () { return this.size; }; /** * Disable transitions on window's frame for the duration of the callback function, then enable them * back. * * @private * @param {Function} callback Function to call while transitions are disabled */ OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) { // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements. // Disable transitions first, otherwise we'll get values from when the window was animating. var oldTransition, styleObj = this.$frame[ 0 ].style; oldTransition = styleObj.transition || styleObj.OTransition || styleObj.MsTransition || styleObj.MozTransition || styleObj.WebkitTransition; styleObj.transition = styleObj.OTransition = styleObj.MsTransition = styleObj.MozTransition = styleObj.WebkitTransition = 'none'; callback(); // Force reflow to make sure the style changes done inside callback really are not transitioned this.$frame.height(); styleObj.transition = styleObj.OTransition = styleObj.MsTransition = styleObj.MozTransition = styleObj.WebkitTransition = oldTransition; }; /** * Get the height of the full window contents (i.e., the window head, body and foot together). * * What consistitutes the head, body, and foot varies depending on the window type. * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body, * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title * and special actions in the head, and dialog content in the body. * * To get just the height of the dialog body, use the #getBodyHeight method. * * @return {number} The height of the window contents (the dialog head, body and foot) in pixels */ OO.ui.Window.prototype.getContentHeight = function () { var bodyHeight, win = this, bodyStyleObj = this.$body[ 0 ].style, frameStyleObj = this.$frame[ 0 ].style; // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements. // Disable transitions first, otherwise we'll get values from when the window was animating. this.withoutSizeTransitions( function () { var oldHeight = frameStyleObj.height, oldPosition = bodyStyleObj.position; frameStyleObj.height = '1px'; // Force body to resize to new width bodyStyleObj.position = 'relative'; bodyHeight = win.getBodyHeight(); frameStyleObj.height = oldHeight; bodyStyleObj.position = oldPosition; } ); return ( // Add buffer for border ( this.$frame.outerHeight() - this.$frame.innerHeight() ) + // Use combined heights of children ( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) ) ); }; /** * Get the height of the window body. * * To get the height of the full window contents (the window body, head, and foot together), * use #getContentHeight. * * When this function is called, the window will temporarily have been resized * to height=1px, so .scrollHeight measurements can be taken accurately. * * @return {number} Height of the window body in pixels */ OO.ui.Window.prototype.getBodyHeight = function () { return this.$body[ 0 ].scrollHeight; }; /** * Get the directionality of the frame (right-to-left or left-to-right). * * @return {string} Directionality: `'ltr'` or `'rtl'` */ OO.ui.Window.prototype.getDir = function () { return this.dir; }; /** * Get the 'setup' process. * * The setup process is used to set up a window for use in a particular context, * based on the `data` argument. This method is called during the opening phase of the window’s * lifecycle. * * Override this method to add additional steps to the ‘setup’ process the parent method provides * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods * of OO.ui.Process. * * To add window content that persists between openings, you may wish to use the #initialize method * instead. * * @abstract * @param {Object} [data] Window opening data * @return {OO.ui.Process} Setup process */ OO.ui.Window.prototype.getSetupProcess = function () { return new OO.ui.Process(); }; /** * Get the ‘ready’ process. * * The ready process is used to ready a window for use in a particular * context, based on the `data` argument. This method is called during the opening phase of * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}. * * Override this method to add additional steps to the ‘ready’ process the parent method * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} * methods of OO.ui.Process. * * @abstract * @param {Object} [data] Window opening data * @return {OO.ui.Process} Ready process */ OO.ui.Window.prototype.getReadyProcess = function () { return new OO.ui.Process(); }; /** * Get the 'hold' process. * * The hold proccess is used to keep a window from being used in a particular context, * based on the `data` argument. This method is called during the closing phase of the window’s * lifecycle. * * Override this method to add additional steps to the 'hold' process the parent method provides * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods * of OO.ui.Process. * * @abstract * @param {Object} [data] Window closing data * @return {OO.ui.Process} Hold process */ OO.ui.Window.prototype.getHoldProcess = function () { return new OO.ui.Process(); }; /** * Get the ‘teardown’ process. * * The teardown process is used to teardown a window after use. During teardown, * user interactions within the window are conveyed and the window is closed, based on the `data` * argument. This method is called during the closing phase of the window’s lifecycle. * * Override this method to add additional steps to the ‘teardown’ process the parent method provides * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods * of OO.ui.Process. * * @abstract * @param {Object} [data] Window closing data * @return {OO.ui.Process} Teardown process */ OO.ui.Window.prototype.getTeardownProcess = function () { return new OO.ui.Process(); }; /** * Set the window manager. * * This will cause the window to initialize. Calling it more than once will cause an error. * * @param {OO.ui.WindowManager} manager Manager for this window * @throws {Error} An error is thrown if the method is called more than once * @chainable */ OO.ui.Window.prototype.setManager = function ( manager ) { if ( this.manager ) { throw new Error( 'Cannot set window manager, window already has a manager' ); } this.manager = manager; this.initialize(); return this; }; /** * Set the window size by symbolic name (e.g., 'small' or 'medium') * * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or * `full` * @chainable */ OO.ui.Window.prototype.setSize = function ( size ) { this.size = size; this.updateSize(); return this; }; /** * Update the window size. * * @throws {Error} An error is thrown if the window is not attached to a window manager * @chainable */ OO.ui.Window.prototype.updateSize = function () { if ( !this.manager ) { throw new Error( 'Cannot update window size, must be attached to a manager' ); } this.manager.updateWindowSize( this ); return this; }; /** * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager} * when the window is opening. In general, setDimensions should not be called directly. * * To set the size of the window, use the #setSize method. * * @param {Object} dim CSS dimension properties * @param {string|number} [dim.width] Width * @param {string|number} [dim.minWidth] Minimum width * @param {string|number} [dim.maxWidth] Maximum width * @param {string|number} [dim.width] Height, omit to set based on height of contents * @param {string|number} [dim.minWidth] Minimum height * @param {string|number} [dim.maxWidth] Maximum height * @chainable */ OO.ui.Window.prototype.setDimensions = function ( dim ) { var height, win = this, styleObj = this.$frame[ 0 ].style; // Calculate the height we need to set using the correct width if ( dim.height === undefined ) { this.withoutSizeTransitions( function () { var oldWidth = styleObj.width; win.$frame.css( 'width', dim.width || '' ); height = win.getContentHeight(); styleObj.width = oldWidth; } ); } else { height = dim.height; } this.$frame.css( { width: dim.width || '', minWidth: dim.minWidth || '', maxWidth: dim.maxWidth || '', height: height || '', minHeight: dim.minHeight || '', maxHeight: dim.maxHeight || '' } ); return this; }; /** * Initialize window contents. * * Before the window is opened for the first time, #initialize is called so that content that * persists between openings can be added to the window. * * To set up a window with new content each time the window opens, use #getSetupProcess. * * @throws {Error} An error is thrown if the window is not attached to a window manager * @chainable */ OO.ui.Window.prototype.initialize = function () { if ( !this.manager ) { throw new Error( 'Cannot initialize window, must be attached to a manager' ); } // Properties this.$head = $( '<div>' ); this.$body = $( '<div>' ); this.$foot = $( '<div>' ); this.dir = OO.ui.Element.static.getDir( this.$content ) || 'ltr'; this.$document = $( this.getElementDocument() ); // Events this.$element.on( 'mousedown', this.onMouseDown.bind( this ) ); // Initialization this.$head.addClass( 'oo-ui-window-head' ); this.$body.addClass( 'oo-ui-window-body' ); this.$foot.addClass( 'oo-ui-window-foot' ); this.$content.append( this.$head, this.$body, this.$foot ); return this; }; /** * Open the window. * * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow} * method, which returns a promise resolved when the window is done opening. * * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess. * * @param {Object} [data] Window opening data * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected * if the window fails to open. When the promise is resolved successfully, the first argument of the * value is a new promise, which is resolved when the window begins closing. * @throws {Error} An error is thrown if the window is not attached to a window manager */ OO.ui.Window.prototype.open = function ( data ) { if ( !this.manager ) { throw new Error( 'Cannot open window, must be attached to a manager' ); } return this.manager.openWindow( this, data ); }; /** * Close the window. * * This method is a wrapper around a call to the window * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method, * which returns a closing promise resolved when the window is done closing. * * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing * phase of the window’s lifecycle and can be used to specify closing behavior each time * the window closes. * * @param {Object} [data] Window closing data * @return {jQuery.Promise} Promise resolved when window is closed * @throws {Error} An error is thrown if the window is not attached to a window manager */ OO.ui.Window.prototype.close = function ( data ) { if ( !this.manager ) { throw new Error( 'Cannot close window, must be attached to a manager' ); } return this.manager.closeWindow( this, data ); }; /** * Setup window. * * This is called by OO.ui.WindowManager during window opening, and should not be called directly * by other systems. * * @param {Object} [data] Window opening data * @return {jQuery.Promise} Promise resolved when window is setup */ OO.ui.Window.prototype.setup = function ( data ) { var win = this, deferred = $.Deferred(); this.toggle( true ); this.getSetupProcess( data ).execute().done( function () { // Force redraw by asking the browser to measure the elements' widths win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width(); win.$content.addClass( 'oo-ui-window-content-setup' ).width(); deferred.resolve(); } ); return deferred.promise(); }; /** * Ready window. * * This is called by OO.ui.WindowManager during window opening, and should not be called directly * by other systems. * * @param {Object} [data] Window opening data * @return {jQuery.Promise} Promise resolved when window is ready */ OO.ui.Window.prototype.ready = function ( data ) { var win = this, deferred = $.Deferred(); this.$content.focus(); this.getReadyProcess( data ).execute().done( function () { // Force redraw by asking the browser to measure the elements' widths win.$element.addClass( 'oo-ui-window-ready' ).width(); win.$content.addClass( 'oo-ui-window-content-ready' ).width(); deferred.resolve(); } ); return deferred.promise(); }; /** * Hold window. * * This is called by OO.ui.WindowManager during window closing, and should not be called directly * by other systems. * * @param {Object} [data] Window closing data * @return {jQuery.Promise} Promise resolved when window is held */ OO.ui.Window.prototype.hold = function ( data ) { var win = this, deferred = $.Deferred(); this.getHoldProcess( data ).execute().done( function () { // Get the focused element within the window's content var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement ); // Blur the focused element if ( $focus.length ) { $focus[ 0 ].blur(); } // Force redraw by asking the browser to measure the elements' widths win.$element.removeClass( 'oo-ui-window-ready' ).width(); win.$content.removeClass( 'oo-ui-window-content-ready' ).width(); deferred.resolve(); } ); return deferred.promise(); }; /** * Teardown window. * * This is called by OO.ui.WindowManager during window closing, and should not be called directly * by other systems. * * @param {Object} [data] Window closing data * @return {jQuery.Promise} Promise resolved when window is torn down */ OO.ui.Window.prototype.teardown = function ( data ) { var win = this; return this.getTeardownProcess( data ).execute() .done( function () { // Force redraw by asking the browser to measure the elements' widths win.$element.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width(); win.$content.removeClass( 'oo-ui-window-content-setup' ).width(); win.toggle( false ); } ); }; /** * The Dialog class serves as the base class for the other types of dialogs. * Unless extended to include controls, the rendered dialog box is a simple window * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager, * which opens, closes, and controls the presentation of the window. See the * [OOjs UI documentation on MediaWiki] [1] for more information. * * @example * // A simple dialog window. * function MyDialog( config ) { * MyDialog.super.call( this, config ); * } * OO.inheritClass( MyDialog, OO.ui.Dialog ); * MyDialog.prototype.initialize = function () { * MyDialog.super.prototype.initialize.call( this ); * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } ); * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' ); * this.$body.append( this.content.$element ); * }; * MyDialog.prototype.getBodyHeight = function () { * return this.content.$element.outerHeight( true ); * }; * var myDialog = new MyDialog( { * size: 'medium' * } ); * // Create and append a window manager, which opens and closes the window. * var windowManager = new OO.ui.WindowManager(); * $( 'body' ).append( windowManager.$element ); * windowManager.addWindows( [ myDialog ] ); * // Open the window! * windowManager.openWindow( myDialog ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs * * @abstract * @class * @extends OO.ui.Window * @mixins OO.ui.PendingElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.Dialog = function OoUiDialog( config ) { // Parent constructor OO.ui.Dialog.super.call( this, config ); // Mixin constructors OO.ui.PendingElement.call( this ); // Properties this.actions = new OO.ui.ActionSet(); this.attachedActions = []; this.currentAction = null; this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this ); // Events this.actions.connect( this, { click: 'onActionClick', resize: 'onActionResize', change: 'onActionsChange' } ); // Initialization this.$element .addClass( 'oo-ui-dialog' ) .attr( 'role', 'dialog' ); }; /* Setup */ OO.inheritClass( OO.ui.Dialog, OO.ui.Window ); OO.mixinClass( OO.ui.Dialog, OO.ui.PendingElement ); /* Static Properties */ /** * Symbolic name of dialog. * * The dialog class must have a symbolic name in order to be registered with OO.Factory. * Please see the [OOjs UI documentation on MediaWiki] [3] for more information. * * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers * * @abstract * @static * @inheritable * @property {string} */ OO.ui.Dialog.static.name = ''; /** * The dialog title. * * The title can be specified as a plaintext string, a {@link OO.ui.LabelElement Label} node, or a function * that will produce a Label node or string. The title can also be specified with data passed to the * constructor (see #getSetupProcess). In this case, the static value will be overriden. * * @abstract * @static * @inheritable * @property {jQuery|string|Function} */ OO.ui.Dialog.static.title = ''; /** * An array of configured {@link OO.ui.ActionWidget action widgets}. * * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static * value will be overriden. * * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets * * @static * @inheritable * @property {Object[]} */ OO.ui.Dialog.static.actions = []; /** * Close the dialog when the 'Esc' key is pressed. * * @static * @abstract * @inheritable * @property {boolean} */ OO.ui.Dialog.static.escapable = true; /* Methods */ /** * Handle frame document key down events. * * @private * @param {jQuery.Event} e Key down event */ OO.ui.Dialog.prototype.onDocumentKeyDown = function ( e ) { if ( e.which === OO.ui.Keys.ESCAPE ) { this.close(); e.preventDefault(); e.stopPropagation(); } }; /** * Handle action resized events. * * @private * @param {OO.ui.ActionWidget} action Action that was resized */ OO.ui.Dialog.prototype.onActionResize = function () { // Override in subclass }; /** * Handle action click events. * * @private * @param {OO.ui.ActionWidget} action Action that was clicked */ OO.ui.Dialog.prototype.onActionClick = function ( action ) { if ( !this.isPending() ) { this.executeAction( action.getAction() ); } }; /** * Handle actions change event. * * @private */ OO.ui.Dialog.prototype.onActionsChange = function () { this.detachActions(); if ( !this.isClosing() ) { this.attachActions(); } }; /** * Get the set of actions used by the dialog. * * @return {OO.ui.ActionSet} */ OO.ui.Dialog.prototype.getActions = function () { return this.actions; }; /** * Get a process for taking action. * * When you override this method, you can create a new OO.ui.Process and return it, or add additional * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'} * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process. * * @abstract * @param {string} [action] Symbolic name of action * @return {OO.ui.Process} Action process */ OO.ui.Dialog.prototype.getActionProcess = function ( action ) { return new OO.ui.Process() .next( function () { if ( !action ) { // An empty action always closes the dialog without data, which should always be // safe and make no changes this.close(); } }, this ); }; /** * @inheritdoc * * @param {Object} [data] Dialog opening data * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use * the {@link #static-title static title} * @param {Object[]} [data.actions] List of configuration options for each * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}. */ OO.ui.Dialog.prototype.getSetupProcess = function ( data ) { data = data || {}; // Parent method return OO.ui.Dialog.super.prototype.getSetupProcess.call( this, data ) .next( function () { var config = this.constructor.static, actions = data.actions !== undefined ? data.actions : config.actions; this.title.setLabel( data.title !== undefined ? data.title : this.constructor.static.title ); this.actions.add( this.getActionWidgets( actions ) ); if ( this.constructor.static.escapable ) { this.$document.on( 'keydown', this.onDocumentKeyDownHandler ); } }, this ); }; /** * @inheritdoc */ OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) { // Parent method return OO.ui.Dialog.super.prototype.getTeardownProcess.call( this, data ) .first( function () { if ( this.constructor.static.escapable ) { this.$document.off( 'keydown', this.onDocumentKeyDownHandler ); } this.actions.clear(); this.currentAction = null; }, this ); }; /** * @inheritdoc */ OO.ui.Dialog.prototype.initialize = function () { // Parent method OO.ui.Dialog.super.prototype.initialize.call( this ); // Properties this.title = new OO.ui.LabelWidget(); // Initialization this.$content.addClass( 'oo-ui-dialog-content' ); this.setPendingElement( this.$head ); }; /** * Get action widgets from a list of configs * * @param {Object[]} actions Action widget configs * @return {OO.ui.ActionWidget[]} Action widgets */ OO.ui.Dialog.prototype.getActionWidgets = function ( actions ) { var i, len, widgets = []; for ( i = 0, len = actions.length; i < len; i++ ) { widgets.push( new OO.ui.ActionWidget( actions[ i ] ) ); } return widgets; }; /** * Attach action actions. * * @protected */ OO.ui.Dialog.prototype.attachActions = function () { // Remember the list of potentially attached actions this.attachedActions = this.actions.get(); }; /** * Detach action actions. * * @protected * @chainable */ OO.ui.Dialog.prototype.detachActions = function () { var i, len; // Detach all actions that may have been previously attached for ( i = 0, len = this.attachedActions.length; i < len; i++ ) { this.attachedActions[ i ].$element.detach(); } this.attachedActions = []; }; /** * Execute an action. * * @param {string} action Symbolic name of action to execute * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails */ OO.ui.Dialog.prototype.executeAction = function ( action ) { this.pushPending(); this.currentAction = action; return this.getActionProcess( action ).execute() .always( this.popPending.bind( this ) ); }; /** * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation. * Managed windows are mutually exclusive. If a new window is opened while a current window is opening * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows * themselves are persistent and—rather than being torn down when closed—can be repopulated with the * pertinent data and reused. * * Over the lifecycle of a window, the window manager makes available three promises: `opening`, * `opened`, and `closing`, which represent the primary stages of the cycle: * * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window. * * - an `opening` event is emitted with an `opening` promise * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the * window and its result executed * - a `setup` progress notification is emitted from the `opening` promise * - the #getReadyDelay method is called the returned value is used to time a pause in execution before * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the * window and its result executed * - a `ready` progress notification is emitted from the `opening` promise * - the `opening` promise is resolved with an `opened` promise * * **Opened**: the window is now open. * * **Closing**: the closing stage begins when the window manager's #closeWindow or the * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins * to close the window. * * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the * window and its result executed * - a `hold` progress notification is emitted from the `closing` promise * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the * window and its result executed * - a `teardown` progress notification is emitted from the `closing` promise * - the `closing` promise is resolved. The window is now closed * * See the [OOjs UI documentation on MediaWiki][1] for more information. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers * * @class * @extends OO.ui.Element * @mixins OO.EventEmitter * * @constructor * @param {Object} [config] Configuration options * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation * Note that window classes that are instantiated with a factory must have * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name. * @cfg {boolean} [modal=true] Prevent interaction outside the dialog */ OO.ui.WindowManager = function OoUiWindowManager( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.WindowManager.super.call( this, config ); // Mixin constructors OO.EventEmitter.call( this ); // Properties this.factory = config.factory; this.modal = config.modal === undefined || !!config.modal; this.windows = {}; this.opening = null; this.opened = null; this.closing = null; this.preparingToOpen = null; this.preparingToClose = null; this.currentWindow = null; this.globalEvents = false; this.$ariaHidden = null; this.onWindowResizeTimeout = null; this.onWindowResizeHandler = this.onWindowResize.bind( this ); this.afterWindowResizeHandler = this.afterWindowResize.bind( this ); // Initialization this.$element .addClass( 'oo-ui-windowManager' ) .toggleClass( 'oo-ui-windowManager-modal', this.modal ); }; /* Setup */ OO.inheritClass( OO.ui.WindowManager, OO.ui.Element ); OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter ); /* Events */ /** * An 'opening' event is emitted when the window begins to be opened. * * @event opening * @param {OO.ui.Window} win Window that's being opened * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully. * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete. * @param {Object} data Window opening data */ /** * A 'closing' event is emitted when the window begins to be closed. * * @event closing * @param {OO.ui.Window} win Window that's being closed * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window * is closed successfully. The promise emits `hold` and `teardown` notifications when those * processes are complete. When the `closing` promise is resolved, the first argument of its value * is the closing data. * @param {Object} data Window closing data */ /** * A 'resize' event is emitted when a window is resized. * * @event resize * @param {OO.ui.Window} win Window that was resized */ /* Static Properties */ /** * Map of the symbolic name of each window size and its CSS properties. * * @static * @inheritable * @property {Object} */ OO.ui.WindowManager.static.sizes = { small: { width: 300 }, medium: { width: 500 }, large: { width: 700 }, larger: { width: 900 }, full: { // These can be non-numeric because they are never used in calculations width: '100%', height: '100%' } }; /** * Symbolic name of the default window size. * * The default size is used if the window's requested size is not recognized. * * @static * @inheritable * @property {string} */ OO.ui.WindowManager.static.defaultSize = 'medium'; /* Methods */ /** * Handle window resize events. * * @private * @param {jQuery.Event} e Window resize event */ OO.ui.WindowManager.prototype.onWindowResize = function () { clearTimeout( this.onWindowResizeTimeout ); this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 ); }; /** * Handle window resize events. * * @private * @param {jQuery.Event} e Window resize event */ OO.ui.WindowManager.prototype.afterWindowResize = function () { if ( this.currentWindow ) { this.updateWindowSize( this.currentWindow ); } }; /** * Check if window is opening. * * @return {boolean} Window is opening */ OO.ui.WindowManager.prototype.isOpening = function ( win ) { return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending'; }; /** * Check if window is closing. * * @return {boolean} Window is closing */ OO.ui.WindowManager.prototype.isClosing = function ( win ) { return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending'; }; /** * Check if window is opened. * * @return {boolean} Window is opened */ OO.ui.WindowManager.prototype.isOpened = function ( win ) { return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending'; }; /** * Check if a window is being managed. * * @param {OO.ui.Window} win Window to check * @return {boolean} Window is being managed */ OO.ui.WindowManager.prototype.hasWindow = function ( win ) { var name; for ( name in this.windows ) { if ( this.windows[ name ] === win ) { return true; } } return false; }; /** * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process. * * @param {OO.ui.Window} win Window being opened * @param {Object} [data] Window opening data * @return {number} Milliseconds to wait */ OO.ui.WindowManager.prototype.getSetupDelay = function () { return 0; }; /** * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process. * * @param {OO.ui.Window} win Window being opened * @param {Object} [data] Window opening data * @return {number} Milliseconds to wait */ OO.ui.WindowManager.prototype.getReadyDelay = function () { return 0; }; /** * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process. * * @param {OO.ui.Window} win Window being closed * @param {Object} [data] Window closing data * @return {number} Milliseconds to wait */ OO.ui.WindowManager.prototype.getHoldDelay = function () { return 0; }; /** * Get the number of milliseconds to wait after the ‘hold’ process has finished before * executing the ‘teardown’ process. * * @param {OO.ui.Window} win Window being closed * @param {Object} [data] Window closing data * @return {number} Milliseconds to wait */ OO.ui.WindowManager.prototype.getTeardownDelay = function () { return this.modal ? 250 : 0; }; /** * Get a window by its symbolic name. * * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3] * for more information about using factories. * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers * * @param {string} name Symbolic name of the window * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory. * @throws {Error} An error is thrown if the named window is not recognized as a managed window. */ OO.ui.WindowManager.prototype.getWindow = function ( name ) { var deferred = $.Deferred(), win = this.windows[ name ]; if ( !( win instanceof OO.ui.Window ) ) { if ( this.factory ) { if ( !this.factory.lookup( name ) ) { deferred.reject( new OO.ui.Error( 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory' ) ); } else { win = this.factory.create( name ); this.addWindows( [ win ] ); deferred.resolve( win ); } } else { deferred.reject( new OO.ui.Error( 'Cannot get unmanaged window: symbolic name unrecognized as a managed window' ) ); } } else { deferred.resolve( win ); } return deferred.promise(); }; /** * Get current window. * * @return {OO.ui.Window|null} Currently opening/opened/closing window */ OO.ui.WindowManager.prototype.getCurrentWindow = function () { return this.currentWindow; }; /** * Open a window. * * @param {OO.ui.Window|string} win Window object or symbolic name of window to open * @param {Object} [data] Window opening data * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening. * See {@link #event-opening 'opening' event} for more information about `opening` promises. * @fires opening */ OO.ui.WindowManager.prototype.openWindow = function ( win, data ) { var manager = this, opening = $.Deferred(); // Argument handling if ( typeof win === 'string' ) { return this.getWindow( win ).then( function ( win ) { return manager.openWindow( win, data ); } ); } // Error handling if ( !this.hasWindow( win ) ) { opening.reject( new OO.ui.Error( 'Cannot open window: window is not attached to manager' ) ); } else if ( this.preparingToOpen || this.opening || this.opened ) { opening.reject( new OO.ui.Error( 'Cannot open window: another window is opening or open' ) ); } // Window opening if ( opening.state() !== 'rejected' ) { // If a window is currently closing, wait for it to complete this.preparingToOpen = $.when( this.closing ); // Ensure handlers get called after preparingToOpen is set this.preparingToOpen.done( function () { if ( manager.modal ) { manager.toggleGlobalEvents( true ); manager.toggleAriaIsolation( true ); } manager.currentWindow = win; manager.opening = opening; manager.preparingToOpen = null; manager.emit( 'opening', win, opening, data ); setTimeout( function () { win.setup( data ).then( function () { manager.updateWindowSize( win ); manager.opening.notify( { state: 'setup' } ); setTimeout( function () { win.ready( data ).then( function () { manager.opening.notify( { state: 'ready' } ); manager.opening = null; manager.opened = $.Deferred(); opening.resolve( manager.opened.promise(), data ); } ); }, manager.getReadyDelay() ); } ); }, manager.getSetupDelay() ); } ); } return opening.promise(); }; /** * Close a window. * * @param {OO.ui.Window|string} win Window object or symbolic name of window to close * @param {Object} [data] Window closing data * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing. * See {@link #event-closing 'closing' event} for more information about closing promises. * @throws {Error} An error is thrown if the window is not managed by the window manager. * @fires closing */ OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) { var manager = this, closing = $.Deferred(), opened; // Argument handling if ( typeof win === 'string' ) { win = this.windows[ win ]; } else if ( !this.hasWindow( win ) ) { win = null; } // Error handling if ( !win ) { closing.reject( new OO.ui.Error( 'Cannot close window: window is not attached to manager' ) ); } else if ( win !== this.currentWindow ) { closing.reject( new OO.ui.Error( 'Cannot close window: window already closed with different data' ) ); } else if ( this.preparingToClose || this.closing ) { closing.reject( new OO.ui.Error( 'Cannot close window: window already closing with different data' ) ); } // Window closing if ( closing.state() !== 'rejected' ) { // If the window is currently opening, close it when it's done this.preparingToClose = $.when( this.opening ); // Ensure handlers get called after preparingToClose is set this.preparingToClose.done( function () { manager.closing = closing; manager.preparingToClose = null; manager.emit( 'closing', win, closing, data ); opened = manager.opened; manager.opened = null; opened.resolve( closing.promise(), data ); setTimeout( function () { win.hold( data ).then( function () { closing.notify( { state: 'hold' } ); setTimeout( function () { win.teardown( data ).then( function () { closing.notify( { state: 'teardown' } ); if ( manager.modal ) { manager.toggleGlobalEvents( false ); manager.toggleAriaIsolation( false ); } manager.closing = null; manager.currentWindow = null; closing.resolve( data ); } ); }, manager.getTeardownDelay() ); } ); }, manager.getHoldDelay() ); } ); } return closing.promise(); }; /** * Add windows to the window manager. * * Windows can be added by reference, symbolic name, or explicitly defined symbolic names. * See the [OOjs ui documentation on MediaWiki] [2] for examples. * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers * * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified * by reference, symbolic name, or explicitly defined symbolic names. * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an * explicit nor a statically configured symbolic name. */ OO.ui.WindowManager.prototype.addWindows = function ( windows ) { var i, len, win, name, list; if ( Array.isArray( windows ) ) { // Convert to map of windows by looking up symbolic names from static configuration list = {}; for ( i = 0, len = windows.length; i < len; i++ ) { name = windows[ i ].constructor.static.name; if ( typeof name !== 'string' ) { throw new Error( 'Cannot add window' ); } list[ name ] = windows[ i ]; } } else if ( OO.isPlainObject( windows ) ) { list = windows; } // Add windows for ( name in list ) { win = list[ name ]; this.windows[ name ] = win.toggle( false ); this.$element.append( win.$element ); win.setManager( this ); } }; /** * Remove the specified windows from the windows manager. * * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no * longer listens to events, use the #destroy method. * * @param {string[]} names Symbolic names of windows to remove * @return {jQuery.Promise} Promise resolved when window is closed and removed * @throws {Error} An error is thrown if the named windows are not managed by the window manager. */ OO.ui.WindowManager.prototype.removeWindows = function ( names ) { var i, len, win, name, cleanupWindow, manager = this, promises = [], cleanup = function ( name, win ) { delete manager.windows[ name ]; win.$element.detach(); }; for ( i = 0, len = names.length; i < len; i++ ) { name = names[ i ]; win = this.windows[ name ]; if ( !win ) { throw new Error( 'Cannot remove window' ); } cleanupWindow = cleanup.bind( null, name, win ); promises.push( this.closeWindow( name ).then( cleanupWindow, cleanupWindow ) ); } return $.when.apply( $, promises ); }; /** * Remove all windows from the window manager. * * Windows will be closed before they are removed. Note that the window manager, though not in use, will still * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead. * To remove just a subset of windows, use the #removeWindows method. * * @return {jQuery.Promise} Promise resolved when all windows are closed and removed */ OO.ui.WindowManager.prototype.clearWindows = function () { return this.removeWindows( Object.keys( this.windows ) ); }; /** * Set dialog size. In general, this method should not be called directly. * * Fullscreen mode will be used if the dialog is too wide to fit in the screen. * * @chainable */ OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) { // Bypass for non-current, and thus invisible, windows if ( win !== this.currentWindow ) { return; } var viewport = OO.ui.Element.static.getDimensions( win.getElementWindow() ), sizes = this.constructor.static.sizes, size = win.getSize(); if ( !sizes[ size ] ) { size = this.constructor.static.defaultSize; } if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) { size = 'full'; } this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', size === 'full' ); this.$element.toggleClass( 'oo-ui-windowManager-floating', size !== 'full' ); win.setDimensions( sizes[ size ] ); this.emit( 'resize', win ); return this; }; /** * Bind or unbind global events for scrolling. * * @private * @param {boolean} [on] Bind global events * @chainable */ OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) { on = on === undefined ? !!this.globalEvents : !!on; var scrollWidth, bodyMargin, $body = $( this.getElementDocument().body ), // We could have multiple window managers open so only modify // the body css at the bottom of the stack stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0 ; if ( on ) { if ( !this.globalEvents ) { $( this.getElementWindow() ).on( { // Start listening for top-level window dimension changes 'orientationchange resize': this.onWindowResizeHandler } ); if ( stackDepth === 0 ) { scrollWidth = window.innerWidth - document.documentElement.clientWidth; bodyMargin = parseFloat( $body.css( 'margin-right' ) ) || 0; $body.css( { overflow: 'hidden', 'margin-right': bodyMargin + scrollWidth } ); } stackDepth++; this.globalEvents = true; } } else if ( this.globalEvents ) { $( this.getElementWindow() ).off( { // Stop listening for top-level window dimension changes 'orientationchange resize': this.onWindowResizeHandler } ); stackDepth--; if ( stackDepth === 0 ) { $body.css( { overflow: '', 'margin-right': '' } ); } this.globalEvents = false; } $body.data( 'windowManagerGlobalEvents', stackDepth ); return this; }; /** * Toggle screen reader visibility of content other than the window manager. * * @private * @param {boolean} [isolate] Make only the window manager visible to screen readers * @chainable */ OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) { isolate = isolate === undefined ? !this.$ariaHidden : !!isolate; if ( isolate ) { if ( !this.$ariaHidden ) { // Hide everything other than the window manager from screen readers this.$ariaHidden = $( 'body' ) .children() .not( this.$element.parentsUntil( 'body' ).last() ) .attr( 'aria-hidden', '' ); } } else if ( this.$ariaHidden ) { // Restore screen reader visibility this.$ariaHidden.removeAttr( 'aria-hidden' ); this.$ariaHidden = null; } return this; }; /** * Destroy the window manager. * * Destroying the window manager ensures that it will no longer listen to events. If you would like to * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method * instead. */ OO.ui.WindowManager.prototype.destroy = function () { this.toggleGlobalEvents( false ); this.toggleAriaIsolation( false ); this.clearWindows(); this.$element.remove(); }; /** * @class * * @constructor * @param {string|jQuery} message Description of error * @param {Object} [config] Configuration options * @cfg {boolean} [recoverable=true] Error is recoverable * @cfg {boolean} [warning=false] Whether this error is a warning or not. */ OO.ui.Error = function OoUiError( message, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( message ) && config === undefined ) { config = message; message = config.message; } // Configuration initialization config = config || {}; // Properties this.message = message instanceof jQuery ? message : String( message ); this.recoverable = config.recoverable === undefined || !!config.recoverable; this.warning = !!config.warning; }; /* Setup */ OO.initClass( OO.ui.Error ); /* Methods */ /** * Check if error can be recovered from. * * @return {boolean} Error is recoverable */ OO.ui.Error.prototype.isRecoverable = function () { return this.recoverable; }; /** * Check if the error is a warning * * @return {boolean} Error is warning */ OO.ui.Error.prototype.isWarning = function () { return this.warning; }; /** * Get error message as DOM nodes. * * @return {jQuery} Error message in DOM nodes */ OO.ui.Error.prototype.getMessage = function () { return this.message instanceof jQuery ? this.message.clone() : $( '<div>' ).text( this.message ).contents(); }; /** * Get error message as text. * * @return {string} Error message */ OO.ui.Error.prototype.getMessageText = function () { return this.message instanceof jQuery ? this.message.text() : this.message; }; /** * Wraps an HTML snippet for use with configuration values which default * to strings. This bypasses the default html-escaping done to string * values. * * @class * * @constructor * @param {string} [content] HTML content */ OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) { // Properties this.content = content; }; /* Setup */ OO.initClass( OO.ui.HtmlSnippet ); /* Methods */ /** * Render into HTML. * * @return {string} Unchanged HTML snippet. */ OO.ui.HtmlSnippet.prototype.toString = function () { return this.content; }; /** * A list of functions, called in sequence. * * If a function added to a process returns boolean false the process will stop; if it returns an * object with a `promise` method the process will use the promise to either continue to the next * step when the promise is resolved or stop when the promise is rejected. * * @class * * @constructor * @param {number|jQuery.Promise|Function} step Time to wait, promise to wait for or function to * call, see #createStep for more information * @param {Object} [context=null] Context to call the step function in, ignored if step is a number * or a promise * @return {Object} Step object, with `callback` and `context` properties */ OO.ui.Process = function ( step, context ) { // Properties this.steps = []; // Initialization if ( step !== undefined ) { this.next( step, context ); } }; /* Setup */ OO.initClass( OO.ui.Process ); /* Methods */ /** * Start the process. * * @return {jQuery.Promise} Promise that is resolved when all steps have completed or rejected when * any of the steps return boolean false or a promise which gets rejected; upon stopping the * process, the remaining steps will not be taken */ OO.ui.Process.prototype.execute = function () { var i, len, promise; /** * Continue execution. * * @ignore * @param {Array} step A function and the context it should be called in * @return {Function} Function that continues the process */ function proceed( step ) { return function () { // Execute step in the correct context var deferred, result = step.callback.call( step.context ); if ( result === false ) { // Use rejected promise for boolean false results return $.Deferred().reject( [] ).promise(); } if ( typeof result === 'number' ) { if ( result < 0 ) { throw new Error( 'Cannot go back in time: flux capacitor is out of service' ); } // Use a delayed promise for numbers, expecting them to be in milliseconds deferred = $.Deferred(); setTimeout( deferred.resolve, result ); return deferred.promise(); } if ( result instanceof OO.ui.Error ) { // Use rejected promise for error return $.Deferred().reject( [ result ] ).promise(); } if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) { // Use rejected promise for list of errors return $.Deferred().reject( result ).promise(); } // Duck-type the object to see if it can produce a promise if ( result && $.isFunction( result.promise ) ) { // Use a promise generated from the result return result.promise(); } // Use resolved promise for other results return $.Deferred().resolve().promise(); }; } if ( this.steps.length ) { // Generate a chain reaction of promises promise = proceed( this.steps[ 0 ] )(); for ( i = 1, len = this.steps.length; i < len; i++ ) { promise = promise.then( proceed( this.steps[ i ] ) ); } } else { promise = $.Deferred().resolve().promise(); } return promise; }; /** * Create a process step. * * @private * @param {number|jQuery.Promise|Function} step * * - Number of milliseconds to wait; or * - Promise to wait to be resolved; or * - Function to execute * - If it returns boolean false the process will stop * - If it returns an object with a `promise` method the process will use the promise to either * continue to the next step when the promise is resolved or stop when the promise is rejected * - If it returns a number, the process will wait for that number of milliseconds before * proceeding * @param {Object} [context=null] Context to call the step function in, ignored if step is a number * or a promise * @return {Object} Step object, with `callback` and `context` properties */ OO.ui.Process.prototype.createStep = function ( step, context ) { if ( typeof step === 'number' || $.isFunction( step.promise ) ) { return { callback: function () { return step; }, context: null }; } if ( $.isFunction( step ) ) { return { callback: step, context: context }; } throw new Error( 'Cannot create process step: number, promise or function expected' ); }; /** * Add step to the beginning of the process. * * @inheritdoc #createStep * @return {OO.ui.Process} this * @chainable */ OO.ui.Process.prototype.first = function ( step, context ) { this.steps.unshift( this.createStep( step, context ) ); return this; }; /** * Add step to the end of the process. * * @inheritdoc #createStep * @return {OO.ui.Process} this * @chainable */ OO.ui.Process.prototype.next = function ( step, context ) { this.steps.push( this.createStep( step, context ) ); return this; }; /** * Factory for tools. * * @class * @extends OO.Factory * @constructor */ OO.ui.ToolFactory = function OoUiToolFactory() { // Parent constructor OO.ui.ToolFactory.super.call( this ); }; /* Setup */ OO.inheritClass( OO.ui.ToolFactory, OO.Factory ); /* Methods */ /** * Get tools from the factory * * @param {Array} include Included tools * @param {Array} exclude Excluded tools * @param {Array} promote Promoted tools * @param {Array} demote Demoted tools * @return {string[]} List of tools */ OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) { var i, len, included, promoted, demoted, auto = [], used = {}; // Collect included and not excluded tools included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) ); // Promotion promoted = this.extract( promote, used ); demoted = this.extract( demote, used ); // Auto for ( i = 0, len = included.length; i < len; i++ ) { if ( !used[ included[ i ] ] ) { auto.push( included[ i ] ); } } return promoted.concat( auto ).concat( demoted ); }; /** * Get a flat list of names from a list of names or groups. * * Tools can be specified in the following ways: * * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'` * - All tools in a group: `{ group: 'group-name' }` * - All tools: `'*'` * * @private * @param {Array|string} collection List of tools * @param {Object} [used] Object with names that should be skipped as properties; extracted * names will be added as properties * @return {string[]} List of extracted names */ OO.ui.ToolFactory.prototype.extract = function ( collection, used ) { var i, len, item, name, tool, names = []; if ( collection === '*' ) { for ( name in this.registry ) { tool = this.registry[ name ]; if ( // Only add tools by group name when auto-add is enabled tool.static.autoAddToCatchall && // Exclude already used tools ( !used || !used[ name ] ) ) { names.push( name ); if ( used ) { used[ name ] = true; } } } } else if ( Array.isArray( collection ) ) { for ( i = 0, len = collection.length; i < len; i++ ) { item = collection[ i ]; // Allow plain strings as shorthand for named tools if ( typeof item === 'string' ) { item = { name: item }; } if ( OO.isPlainObject( item ) ) { if ( item.group ) { for ( name in this.registry ) { tool = this.registry[ name ]; if ( // Include tools with matching group tool.static.group === item.group && // Only add tools by group name when auto-add is enabled tool.static.autoAddToGroup && // Exclude already used tools ( !used || !used[ name ] ) ) { names.push( name ); if ( used ) { used[ name ] = true; } } } // Include tools with matching name and exclude already used tools } else if ( item.name && ( !used || !used[ item.name ] ) ) { names.push( item.name ); if ( used ) { used[ item.name ] = true; } } } } } return names; }; /** * Factory for tool groups. * * @class * @extends OO.Factory * @constructor */ OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() { // Parent constructor OO.Factory.call( this ); var i, l, defaultClasses = this.constructor.static.getDefaultClasses(); // Register default toolgroups for ( i = 0, l = defaultClasses.length; i < l; i++ ) { this.register( defaultClasses[ i ] ); } }; /* Setup */ OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory ); /* Static Methods */ /** * Get a default set of classes to be registered on construction * * @return {Function[]} Default classes */ OO.ui.ToolGroupFactory.static.getDefaultClasses = function () { return [ OO.ui.BarToolGroup, OO.ui.ListToolGroup, OO.ui.MenuToolGroup ]; }; /** * Theme logic. * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options */ OO.ui.Theme = function OoUiTheme( config ) { // Configuration initialization config = config || {}; }; /* Setup */ OO.initClass( OO.ui.Theme ); /* Methods */ /** * Get a list of classes to be applied to a widget. * * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes, * otherwise state transitions will not work properly. * * @param {OO.ui.Element} element Element for which to get classes * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists */ OO.ui.Theme.prototype.getElementClasses = function ( /* element */ ) { return { on: [], off: [] }; }; /** * Update CSS classes provided by the theme. * * For elements with theme logic hooks, this should be called any time there's a state change. * * @param {OO.ui.Element} element Element for which to update classes * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists */ OO.ui.Theme.prototype.updateElementClasses = function ( element ) { var classes = this.getElementClasses( element ); element.$element .removeClass( classes.off.join( ' ' ) ) .addClass( classes.on.join( ' ' ) ); }; /** * The TabIndexedElement class is an attribute mixin used to add additional functionality to an * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the * order in which users will navigate through the focusable elements via the "tab" key. * * @example * // TabIndexedElement is mixed into the ButtonWidget class * // to provide a tabIndex property. * var button1 = new OO.ui.ButtonWidget( { * label: 'fourth', * tabIndex: 4 * } ); * var button2 = new OO.ui.ButtonWidget( { * label: 'second', * tabIndex: 2 * } ); * var button3 = new OO.ui.ButtonWidget( { * label: 'third', * tabIndex: 3 * } ); * var button4 = new OO.ui.ButtonWidget( { * label: 'first', * tabIndex: 1 * } ); * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element ); * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default, * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex * functionality will be applied to it instead. * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1 * to remove the element from the tab-navigation flow. */ OO.ui.TabIndexedElement = function OoUiTabIndexedElement( config ) { // Configuration initialization config = $.extend( { tabIndex: 0 }, config ); // Properties this.$tabIndexed = null; this.tabIndex = null; // Events this.connect( this, { disable: 'onDisable' } ); // Initialization this.setTabIndex( config.tabIndex ); this.setTabIndexedElement( config.$tabIndexed || this.$element ); }; /* Setup */ OO.initClass( OO.ui.TabIndexedElement ); /* Methods */ /** * Set the element that should use the tabindex functionality. * * This method is used to retarget a tabindex mixin so that its functionality applies * to the specified element. If an element is currently using the functionality, the mixin’s * effect on that element is removed before the new element is set up. * * @param {jQuery} $tabIndexed Element that should use the tabindex functionality * @chainable */ OO.ui.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) { var tabIndex = this.tabIndex; // Remove attributes from old $tabIndexed this.setTabIndex( null ); // Force update of new $tabIndexed this.$tabIndexed = $tabIndexed; this.tabIndex = tabIndex; return this.updateTabIndex(); }; /** * Set the value of the tabindex. * * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex * @chainable */ OO.ui.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) { tabIndex = typeof tabIndex === 'number' ? tabIndex : null; if ( this.tabIndex !== tabIndex ) { this.tabIndex = tabIndex; this.updateTabIndex(); } return this; }; /** * Update the `tabindex` attribute, in case of changes to tab index or * disabled state. * * @private * @chainable */ OO.ui.TabIndexedElement.prototype.updateTabIndex = function () { if ( this.$tabIndexed ) { if ( this.tabIndex !== null ) { // Do not index over disabled elements this.$tabIndexed.attr( { tabindex: this.isDisabled() ? -1 : this.tabIndex, // ChromeVox and NVDA do not seem to inherit this from parent elements 'aria-disabled': this.isDisabled().toString() } ); } else { this.$tabIndexed.removeAttr( 'tabindex aria-disabled' ); } } return this; }; /** * Handle disable events. * * @private * @param {boolean} disabled Element is disabled */ OO.ui.TabIndexedElement.prototype.onDisable = function () { this.updateTabIndex(); }; /** * Get the value of the tabindex. * * @return {number|null} Tabindex value */ OO.ui.TabIndexedElement.prototype.getTabIndex = function () { return this.tabIndex; }; /** * ButtonElement is often mixed into other classes to generate a button, which is a clickable * interface element that can be configured with access keys for accessibility. * See the [OOjs UI documentation on MediaWiki] [1] for examples. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$button] The button element created by the class. * If this configuration is omitted, the button element will use a generated `<a>`. * @cfg {boolean} [framed=true] Render the button with a frame * @cfg {string} [accessKey] Button's access key */ OO.ui.ButtonElement = function OoUiButtonElement( config ) { // Configuration initialization config = config || {}; // Properties this.$button = null; this.framed = null; this.accessKey = null; this.active = false; this.onMouseUpHandler = this.onMouseUp.bind( this ); this.onMouseDownHandler = this.onMouseDown.bind( this ); this.onKeyDownHandler = this.onKeyDown.bind( this ); this.onKeyUpHandler = this.onKeyUp.bind( this ); this.onClickHandler = this.onClick.bind( this ); this.onKeyPressHandler = this.onKeyPress.bind( this ); // Initialization this.$element.addClass( 'oo-ui-buttonElement' ); this.toggleFramed( config.framed === undefined || config.framed ); this.setAccessKey( config.accessKey ); this.setButtonElement( config.$button || $( '<a>' ) ); }; /* Setup */ OO.initClass( OO.ui.ButtonElement ); /* Static Properties */ /** * Cancel mouse down events. * * This property is usually set to `true` to prevent the focus from changing when the button is clicked. * Classes such as {@link OO.ui.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a * parent widget. * * @static * @inheritable * @property {boolean} */ OO.ui.ButtonElement.static.cancelButtonMouseDownEvents = true; /* Events */ /** * A 'click' event is emitted when the button element is clicked. * * @event click */ /* Methods */ /** * Set the button element. * * This method is used to retarget a button mixin so that its functionality applies to * the specified button element instead of the one created by the class. If a button element * is already set, the method will remove the mixin’s effect on that element. * * @param {jQuery} $button Element to use as button */ OO.ui.ButtonElement.prototype.setButtonElement = function ( $button ) { if ( this.$button ) { this.$button .removeClass( 'oo-ui-buttonElement-button' ) .removeAttr( 'role accesskey' ) .off( { mousedown: this.onMouseDownHandler, keydown: this.onKeyDownHandler, click: this.onClickHandler, keypress: this.onKeyPressHandler } ); } this.$button = $button .addClass( 'oo-ui-buttonElement-button' ) .attr( { role: 'button', accesskey: this.accessKey } ) .on( { mousedown: this.onMouseDownHandler, keydown: this.onKeyDownHandler, click: this.onClickHandler, keypress: this.onKeyPressHandler } ); }; /** * Handles mouse down events. * * @protected * @param {jQuery.Event} e Mouse down event */ OO.ui.ButtonElement.prototype.onMouseDown = function ( e ) { if ( this.isDisabled() || e.which !== 1 ) { return; } this.$element.addClass( 'oo-ui-buttonElement-pressed' ); // Run the mouseup handler no matter where the mouse is when the button is let go, so we can // reliably remove the pressed class this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true ); // Prevent change of focus unless specifically configured otherwise if ( this.constructor.static.cancelButtonMouseDownEvents ) { return false; } }; /** * Handles mouse up events. * * @protected * @param {jQuery.Event} e Mouse up event */ OO.ui.ButtonElement.prototype.onMouseUp = function ( e ) { if ( this.isDisabled() || e.which !== 1 ) { return; } this.$element.removeClass( 'oo-ui-buttonElement-pressed' ); // Stop listening for mouseup, since we only needed this once this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true ); }; /** * Handles mouse click events. * * @protected * @param {jQuery.Event} e Mouse click event * @fires click */ OO.ui.ButtonElement.prototype.onClick = function ( e ) { if ( !this.isDisabled() && e.which === 1 ) { this.emit( 'click' ); } return false; }; /** * Handles key down events. * * @protected * @param {jQuery.Event} e Key down event */ OO.ui.ButtonElement.prototype.onKeyDown = function ( e ) { if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) { return; } this.$element.addClass( 'oo-ui-buttonElement-pressed' ); // Run the keyup handler no matter where the key is when the button is let go, so we can // reliably remove the pressed class this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler, true ); }; /** * Handles key up events. * * @protected * @param {jQuery.Event} e Key up event */ OO.ui.ButtonElement.prototype.onKeyUp = function ( e ) { if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) { return; } this.$element.removeClass( 'oo-ui-buttonElement-pressed' ); // Stop listening for keyup, since we only needed this once this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler, true ); }; /** * Handles key press events. * * @protected * @param {jQuery.Event} e Key press event * @fires click */ OO.ui.ButtonElement.prototype.onKeyPress = function ( e ) { if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) { this.emit( 'click' ); return false; } }; /** * Check if button has a frame. * * @return {boolean} Button is framed */ OO.ui.ButtonElement.prototype.isFramed = function () { return this.framed; }; /** * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off. * * @param {boolean} [framed] Make button framed, omit to toggle * @chainable */ OO.ui.ButtonElement.prototype.toggleFramed = function ( framed ) { framed = framed === undefined ? !this.framed : !!framed; if ( framed !== this.framed ) { this.framed = framed; this.$element .toggleClass( 'oo-ui-buttonElement-frameless', !framed ) .toggleClass( 'oo-ui-buttonElement-framed', framed ); this.updateThemeClasses(); } return this; }; /** * Set the button's access key. * * @param {string} accessKey Button's access key, use empty string to remove * @chainable */ OO.ui.ButtonElement.prototype.setAccessKey = function ( accessKey ) { accessKey = typeof accessKey === 'string' && accessKey.length ? accessKey : null; if ( this.accessKey !== accessKey ) { if ( this.$button ) { if ( accessKey !== null ) { this.$button.attr( 'accesskey', accessKey ); } else { this.$button.removeAttr( 'accesskey' ); } } this.accessKey = accessKey; } return this; }; /** * Set the button to its 'active' state. * * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing * for other button types. * * @param {boolean} [value] Make button active * @chainable */ OO.ui.ButtonElement.prototype.setActive = function ( value ) { this.$element.toggleClass( 'oo-ui-buttonElement-active', !!value ); return this; }; /** * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing * items from the group is done through the interface the class provides. * For more information, please see the [OOjs UI documentation on MediaWiki] [1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$group] The container element created by the class. If this configuration * is omitted, the group element will use a generated `<div>`. */ OO.ui.GroupElement = function OoUiGroupElement( config ) { // Configuration initialization config = config || {}; // Properties this.$group = null; this.items = []; this.aggregateItemEvents = {}; // Initialization this.setGroupElement( config.$group || $( '<div>' ) ); }; /* Methods */ /** * Set the group element. * * If an element is already set, items will be moved to the new element. * * @param {jQuery} $group Element to use as group */ OO.ui.GroupElement.prototype.setGroupElement = function ( $group ) { var i, len; this.$group = $group; for ( i = 0, len = this.items.length; i < len; i++ ) { this.$group.append( this.items[ i ].$element ); } }; /** * Check if a group contains no items. * * @return {boolean} Group is empty */ OO.ui.GroupElement.prototype.isEmpty = function () { return !this.items.length; }; /** * Get all items in the group. * * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful * when synchronizing groups of items, or whenever the references are required (e.g., when removing items * from a group). * * @return {OO.ui.Element[]} An array of items. */ OO.ui.GroupElement.prototype.getItems = function () { return this.items.slice( 0 ); }; /** * Get an item by its data. * * Only the first item with matching data will be returned. To return all matching items, * use the #getItemsFromData method. * * @param {Object} data Item data to search for * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists */ OO.ui.GroupElement.prototype.getItemFromData = function ( data ) { var i, len, item, hash = OO.getHash( data ); for ( i = 0, len = this.items.length; i < len; i++ ) { item = this.items[ i ]; if ( hash === OO.getHash( item.getData() ) ) { return item; } } return null; }; /** * Get items by their data. * * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead. * * @param {Object} data Item data to search for * @return {OO.ui.Element[]} Items with equivalent data */ OO.ui.GroupElement.prototype.getItemsFromData = function ( data ) { var i, len, item, hash = OO.getHash( data ), items = []; for ( i = 0, len = this.items.length; i < len; i++ ) { item = this.items[ i ]; if ( hash === OO.getHash( item.getData() ) ) { items.push( item ); } } return items; }; /** * Aggregate the events emitted by the group. * * When events are aggregated, the group will listen to all contained items for the event, * and then emit the event under a new name. The new event will contain an additional leading * parameter containing the item that emitted the original event. Other arguments emitted from * the original event are passed through. * * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’). * A `null` value will remove aggregated events. * @throws {Error} An error is thrown if aggregation already exists. */ OO.ui.GroupElement.prototype.aggregate = function ( events ) { var i, len, item, add, remove, itemEvent, groupEvent; for ( itemEvent in events ) { groupEvent = events[ itemEvent ]; // Remove existing aggregated event if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) { // Don't allow duplicate aggregations if ( groupEvent ) { throw new Error( 'Duplicate item event aggregation for ' + itemEvent ); } // Remove event aggregation from existing items for ( i = 0, len = this.items.length; i < len; i++ ) { item = this.items[ i ]; if ( item.connect && item.disconnect ) { remove = {}; remove[ itemEvent ] = [ 'emit', groupEvent, item ]; item.disconnect( this, remove ); } } // Prevent future items from aggregating event delete this.aggregateItemEvents[ itemEvent ]; } // Add new aggregate event if ( groupEvent ) { // Make future items aggregate event this.aggregateItemEvents[ itemEvent ] = groupEvent; // Add event aggregation to existing items for ( i = 0, len = this.items.length; i < len; i++ ) { item = this.items[ i ]; if ( item.connect && item.disconnect ) { add = {}; add[ itemEvent ] = [ 'emit', groupEvent, item ]; item.connect( this, add ); } } } } }; /** * Add items to the group. * * Items will be added to the end of the group array unless the optional `index` parameter specifies * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`. * * @param {OO.ui.Element[]} items An array of items to add to the group * @param {number} [index] Index of the insertion point * @chainable */ OO.ui.GroupElement.prototype.addItems = function ( items, index ) { var i, len, item, event, events, currentIndex, itemElements = []; for ( i = 0, len = items.length; i < len; i++ ) { item = items[ i ]; // Check if item exists then remove it first, effectively "moving" it currentIndex = $.inArray( item, this.items ); if ( currentIndex >= 0 ) { this.removeItems( [ item ] ); // Adjust index to compensate for removal if ( currentIndex < index ) { index--; } } // Add the item if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) { events = {}; for ( event in this.aggregateItemEvents ) { events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ]; } item.connect( this, events ); } item.setElementGroup( this ); itemElements.push( item.$element.get( 0 ) ); } if ( index === undefined || index < 0 || index >= this.items.length ) { this.$group.append( itemElements ); this.items.push.apply( this.items, items ); } else if ( index === 0 ) { this.$group.prepend( itemElements ); this.items.unshift.apply( this.items, items ); } else { this.items[ index ].$element.before( itemElements ); this.items.splice.apply( this.items, [ index, 0 ].concat( items ) ); } return this; }; /** * Remove the specified items from a group. * * Removed items are detached (not removed) from the DOM so that they may be reused. * To remove all items from a group, you may wish to use the #clearItems method instead. * * @param {OO.ui.Element[]} items An array of items to remove * @chainable */ OO.ui.GroupElement.prototype.removeItems = function ( items ) { var i, len, item, index, remove, itemEvent; // Remove specific items for ( i = 0, len = items.length; i < len; i++ ) { item = items[ i ]; index = $.inArray( item, this.items ); if ( index !== -1 ) { if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) { remove = {}; if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) { remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ]; } item.disconnect( this, remove ); } item.setElementGroup( null ); this.items.splice( index, 1 ); item.$element.detach(); } } return this; }; /** * Clear all items from the group. * * Cleared items are detached from the DOM, not removed, so that they may be reused. * To remove only a subset of items from a group, use the #removeItems method. * * @chainable */ OO.ui.GroupElement.prototype.clearItems = function () { var i, len, item, remove, itemEvent; // Remove all items for ( i = 0, len = this.items.length; i < len; i++ ) { item = this.items[ i ]; if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) { remove = {}; if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) { remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ]; } item.disconnect( this, remove ); } item.setElementGroup( null ); item.$element.detach(); } this.items = []; return this; }; /** * DraggableElement is a mixin class used to create elements that can be clicked * and dragged by a mouse to a new position within a group. This class must be used * in conjunction with OO.ui.DraggableGroupElement, which provides a container for * the draggable elements. * * @abstract * @class * * @constructor */ OO.ui.DraggableElement = function OoUiDraggableElement() { // Properties this.index = null; // Initialize and events this.$element .attr( 'draggable', true ) .addClass( 'oo-ui-draggableElement' ) .on( { dragstart: this.onDragStart.bind( this ), dragover: this.onDragOver.bind( this ), dragend: this.onDragEnd.bind( this ), drop: this.onDrop.bind( this ) } ); }; OO.initClass( OO.ui.DraggableElement ); /* Events */ /** * @event dragstart * * A dragstart event is emitted when the user clicks and begins dragging an item. * @param {OO.ui.DraggableElement} item The item the user has clicked and is dragging with the mouse. */ /** * @event dragend * A dragend event is emitted when the user drags an item and releases the mouse, * thus terminating the drag operation. */ /** * @event drop * A drop event is emitted when the user drags an item and then releases the mouse button * over a valid target. */ /* Static Properties */ /** * @inheritdoc OO.ui.ButtonElement */ OO.ui.DraggableElement.static.cancelButtonMouseDownEvents = false; /* Methods */ /** * Respond to dragstart event. * * @private * @param {jQuery.Event} event jQuery event * @fires dragstart */ OO.ui.DraggableElement.prototype.onDragStart = function ( e ) { var dataTransfer = e.originalEvent.dataTransfer; // Define drop effect dataTransfer.dropEffect = 'none'; dataTransfer.effectAllowed = 'move'; // We must set up a dataTransfer data property or Firefox seems to // ignore the fact the element is draggable. try { dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() ); } catch ( err ) { // The above is only for firefox. No need to set a catch clause // if it fails, move on. } // Add dragging class this.$element.addClass( 'oo-ui-draggableElement-dragging' ); // Emit event this.emit( 'dragstart', this ); return true; }; /** * Respond to dragend event. * * @private * @fires dragend */ OO.ui.DraggableElement.prototype.onDragEnd = function () { this.$element.removeClass( 'oo-ui-draggableElement-dragging' ); this.emit( 'dragend' ); }; /** * Handle drop event. * * @private * @param {jQuery.Event} event jQuery event * @fires drop */ OO.ui.DraggableElement.prototype.onDrop = function ( e ) { e.preventDefault(); this.emit( 'drop', e ); }; /** * In order for drag/drop to work, the dragover event must * return false and stop propogation. * * @private */ OO.ui.DraggableElement.prototype.onDragOver = function ( e ) { e.preventDefault(); }; /** * Set item index. * Store it in the DOM so we can access from the widget drag event * * @private * @param {number} Item index */ OO.ui.DraggableElement.prototype.setIndex = function ( index ) { if ( this.index !== index ) { this.index = index; this.$element.data( 'index', index ); } }; /** * Get item index * * @private * @return {number} Item index */ OO.ui.DraggableElement.prototype.getIndex = function () { return this.index; }; /** * DraggableGroupElement is a mixin class used to create a group element to * contain draggable elements, which are items that can be clicked and dragged by a mouse. * The class is used with OO.ui.DraggableElement. * * @abstract * @class * @mixins OO.ui.GroupElement * * @constructor * @param {Object} [config] Configuration options * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation * should match the layout of the items. Items displayed in a single row * or in several rows should use horizontal orientation. The vertical orientation should only be * used when the items are displayed in a single column. Defaults to 'vertical' */ OO.ui.DraggableGroupElement = function OoUiDraggableGroupElement( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.GroupElement.call( this, config ); // Properties this.orientation = config.orientation || 'vertical'; this.dragItem = null; this.itemDragOver = null; this.itemKeys = {}; this.sideInsertion = ''; // Events this.aggregate( { dragstart: 'itemDragStart', dragend: 'itemDragEnd', drop: 'itemDrop' } ); this.connect( this, { itemDragStart: 'onItemDragStart', itemDrop: 'onItemDrop', itemDragEnd: 'onItemDragEnd' } ); this.$element.on( { dragover: $.proxy( this.onDragOver, this ), dragleave: $.proxy( this.onDragLeave, this ) } ); // Initialize if ( Array.isArray( config.items ) ) { this.addItems( config.items ); } this.$placeholder = $( '<div>' ) .addClass( 'oo-ui-draggableGroupElement-placeholder' ); this.$element .addClass( 'oo-ui-draggableGroupElement' ) .append( this.$status ) .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' ) .prepend( this.$placeholder ); }; /* Setup */ OO.mixinClass( OO.ui.DraggableGroupElement, OO.ui.GroupElement ); /* Events */ /** * A 'reorder' event is emitted when the order of items in the group changes. * * @event reorder * @param {OO.ui.DraggableElement} item Reordered item * @param {number} [newIndex] New index for the item */ /* Methods */ /** * Respond to item drag start event * * @private * @param {OO.ui.DraggableElement} item Dragged item */ OO.ui.DraggableGroupElement.prototype.onItemDragStart = function ( item ) { var i, len; // Map the index of each object for ( i = 0, len = this.items.length; i < len; i++ ) { this.items[ i ].setIndex( i ); } if ( this.orientation === 'horizontal' ) { // Set the height of the indicator this.$placeholder.css( { height: item.$element.outerHeight(), width: 2 } ); } else { // Set the width of the indicator this.$placeholder.css( { height: 2, width: item.$element.outerWidth() } ); } this.setDragItem( item ); }; /** * Respond to item drag end event * * @private */ OO.ui.DraggableGroupElement.prototype.onItemDragEnd = function () { this.unsetDragItem(); return false; }; /** * Handle drop event and switch the order of the items accordingly * * @private * @param {OO.ui.DraggableElement} item Dropped item * @fires reorder */ OO.ui.DraggableGroupElement.prototype.onItemDrop = function ( item ) { var toIndex = item.getIndex(); // Check if the dropped item is from the current group // TODO: Figure out a way to configure a list of legally droppable // elements even if they are not yet in the list if ( this.getDragItem() ) { // If the insertion point is 'after', the insertion index // is shifted to the right (or to the left in RTL, hence 'after') if ( this.sideInsertion === 'after' ) { toIndex++; } // Emit change event this.emit( 'reorder', this.getDragItem(), toIndex ); } this.unsetDragItem(); // Return false to prevent propogation return false; }; /** * Handle dragleave event. * * @private */ OO.ui.DraggableGroupElement.prototype.onDragLeave = function () { // This means the item was dragged outside the widget this.$placeholder .css( 'left', 0 ) .addClass( 'oo-ui-element-hidden' ); }; /** * Respond to dragover event * * @private * @param {jQuery.Event} event Event details */ OO.ui.DraggableGroupElement.prototype.onDragOver = function ( e ) { var dragOverObj, $optionWidget, itemOffset, itemMidpoint, itemBoundingRect, itemSize, cssOutput, dragPosition, itemIndex, itemPosition, clientX = e.originalEvent.clientX, clientY = e.originalEvent.clientY; // Get the OptionWidget item we are dragging over dragOverObj = this.getElementDocument().elementFromPoint( clientX, clientY ); $optionWidget = $( dragOverObj ).closest( '.oo-ui-draggableElement' ); if ( $optionWidget[ 0 ] ) { itemOffset = $optionWidget.offset(); itemBoundingRect = $optionWidget[ 0 ].getBoundingClientRect(); itemPosition = $optionWidget.position(); itemIndex = $optionWidget.data( 'index' ); } if ( itemOffset && this.isDragging() && itemIndex !== this.getDragItem().getIndex() ) { if ( this.orientation === 'horizontal' ) { // Calculate where the mouse is relative to the item width itemSize = itemBoundingRect.width; itemMidpoint = itemBoundingRect.left + itemSize / 2; dragPosition = clientX; // Which side of the item we hover over will dictate // where the placeholder will appear, on the left or // on the right cssOutput = { left: dragPosition < itemMidpoint ? itemPosition.left : itemPosition.left + itemSize, top: itemPosition.top }; } else { // Calculate where the mouse is relative to the item height itemSize = itemBoundingRect.height; itemMidpoint = itemBoundingRect.top + itemSize / 2; dragPosition = clientY; // Which side of the item we hover over will dictate // where the placeholder will appear, on the top or // on the bottom cssOutput = { top: dragPosition < itemMidpoint ? itemPosition.top : itemPosition.top + itemSize, left: itemPosition.left }; } // Store whether we are before or after an item to rearrange // For horizontal layout, we need to account for RTL, as this is flipped if ( this.orientation === 'horizontal' && this.$element.css( 'direction' ) === 'rtl' ) { this.sideInsertion = dragPosition < itemMidpoint ? 'after' : 'before'; } else { this.sideInsertion = dragPosition < itemMidpoint ? 'before' : 'after'; } // Add drop indicator between objects this.$placeholder .css( cssOutput ) .removeClass( 'oo-ui-element-hidden' ); } else { // This means the item was dragged outside the widget this.$placeholder .css( 'left', 0 ) .addClass( 'oo-ui-element-hidden' ); } // Prevent default e.preventDefault(); }; /** * Set a dragged item * * @param {OO.ui.DraggableElement} item Dragged item */ OO.ui.DraggableGroupElement.prototype.setDragItem = function ( item ) { this.dragItem = item; }; /** * Unset the current dragged item */ OO.ui.DraggableGroupElement.prototype.unsetDragItem = function () { this.dragItem = null; this.itemDragOver = null; this.$placeholder.addClass( 'oo-ui-element-hidden' ); this.sideInsertion = ''; }; /** * Get the item that is currently being dragged. * * @return {OO.ui.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged */ OO.ui.DraggableGroupElement.prototype.getDragItem = function () { return this.dragItem; }; /** * Check if an item in the group is currently being dragged. * * @return {Boolean} Item is being dragged */ OO.ui.DraggableGroupElement.prototype.isDragging = function () { return this.getDragItem() !== null; }; /** * IconElement is often mixed into other classes to generate an icon. * Icons are graphics, about the size of normal text. They are used to aid the user * in locating a control or to convey information in a space-efficient way. See the * [OOjs UI documentation on MediaWiki] [1] for a list of icons * included in the library. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted, * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that * the icon element be set to an existing icon instead of the one generated by this class, set a * value using a jQuery selection. For example: * * // Use a <div> tag instead of a <span> * $icon: $("<div>") * // Use an existing icon element instead of the one generated by the class * $icon: this.$element * // Use an icon element from a child widget * $icon: this.childwidget.$element * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of * symbolic names. A map is used for i18n purposes and contains a `default` icon * name and additional names keyed by language code. The `default` name is used when no icon is keyed * by the user's language. * * Example of an i18n map: * * { default: 'bold-a', en: 'bold-b', de: 'bold-f' } * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library. * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title * text. The icon title is displayed when users move the mouse over the icon. */ OO.ui.IconElement = function OoUiIconElement( config ) { // Configuration initialization config = config || {}; // Properties this.$icon = null; this.icon = null; this.iconTitle = null; // Initialization this.setIcon( config.icon || this.constructor.static.icon ); this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle ); this.setIconElement( config.$icon || $( '<span>' ) ); }; /* Setup */ OO.initClass( OO.ui.IconElement ); /* Static Properties */ /** * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used * for i18n purposes and contains a `default` icon name and additional names keyed by * language code. The `default` name is used when no icon is keyed by the user's language. * * Example of an i18n map: * * { default: 'bold-a', en: 'bold-b', de: 'bold-f' } * * Note: the static property will be overridden if the #icon configuration is used. * * @static * @inheritable * @property {Object|string} */ OO.ui.IconElement.static.icon = null; /** * The icon title, displayed when users move the mouse over the icon. The value can be text, a * function that returns title text, or `null` for no title. * * The static property will be overridden if the #iconTitle configuration is used. * * @static * @inheritable * @property {string|Function|null} */ OO.ui.IconElement.static.iconTitle = null; /* Methods */ /** * Set the icon element. This method is used to retarget an icon mixin so that its functionality * applies to the specified icon element instead of the one created by the class. If an icon * element is already set, the mixin’s effect on that element is removed. Generated CSS classes * and mixin methods will no longer affect the element. * * @param {jQuery} $icon Element to use as icon */ OO.ui.IconElement.prototype.setIconElement = function ( $icon ) { if ( this.$icon ) { this.$icon .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon ) .removeAttr( 'title' ); } this.$icon = $icon .addClass( 'oo-ui-iconElement-icon' ) .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon ); if ( this.iconTitle !== null ) { this.$icon.attr( 'title', this.iconTitle ); } }; /** * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon. * The icon parameter can also be set to a map of icon names. See the #icon config setting * for an example. * * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed * by language code, or `null` to remove the icon. * @chainable */ OO.ui.IconElement.prototype.setIcon = function ( icon ) { icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon; icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null; if ( this.icon !== icon ) { if ( this.$icon ) { if ( this.icon !== null ) { this.$icon.removeClass( 'oo-ui-icon-' + this.icon ); } if ( icon !== null ) { this.$icon.addClass( 'oo-ui-icon-' + icon ); } } this.icon = icon; } this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon ); this.updateThemeClasses(); return this; }; /** * Set the icon title. Use `null` to remove the title. * * @param {string|Function|null} iconTitle A text string used as the icon title, * a function that returns title text, or `null` for no title. * @chainable */ OO.ui.IconElement.prototype.setIconTitle = function ( iconTitle ) { iconTitle = typeof iconTitle === 'function' || ( typeof iconTitle === 'string' && iconTitle.length ) ? OO.ui.resolveMsg( iconTitle ) : null; if ( this.iconTitle !== iconTitle ) { this.iconTitle = iconTitle; if ( this.$icon ) { if ( this.iconTitle !== null ) { this.$icon.attr( 'title', iconTitle ); } else { this.$icon.removeAttr( 'title' ); } } } return this; }; /** * Get the symbolic name of the icon. * * @return {string} Icon name */ OO.ui.IconElement.prototype.getIcon = function () { return this.icon; }; /** * Get the icon title. The title text is displayed when a user moves the mouse over the icon. * * @return {string} Icon title text */ OO.ui.IconElement.prototype.getIconTitle = function () { return this.iconTitle; }; /** * IndicatorElement is often mixed into other classes to generate an indicator. * Indicators are small graphics that are generally used in two ways: * * - To draw attention to the status of an item. For example, an indicator might be * used to show that an item in a list has errors that need to be resolved. * - To clarify the function of a control that acts in an exceptional way (a button * that opens a menu instead of performing an action directly, for example). * * For a list of indicators included in the library, please see the * [OOjs UI documentation on MediaWiki] [1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$indicator] The indicator element created by the class. If this * configuration is omitted, the indicator element will use a generated `<span>`. * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’). * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included * in the library. * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title, * or a function that returns title text. The indicator title is displayed when users move * the mouse over the indicator. */ OO.ui.IndicatorElement = function OoUiIndicatorElement( config ) { // Configuration initialization config = config || {}; // Properties this.$indicator = null; this.indicator = null; this.indicatorTitle = null; // Initialization this.setIndicator( config.indicator || this.constructor.static.indicator ); this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle ); this.setIndicatorElement( config.$indicator || $( '<span>' ) ); }; /* Setup */ OO.initClass( OO.ui.IndicatorElement ); /* Static Properties */ /** * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’). * The static property will be overridden if the #indicator configuration is used. * * @static * @inheritable * @property {string|null} */ OO.ui.IndicatorElement.static.indicator = null; /** * A text string used as the indicator title, a function that returns title text, or `null` * for no title. The static property will be overridden if the #indicatorTitle configuration is used. * * @static * @inheritable * @property {string|Function|null} */ OO.ui.IndicatorElement.static.indicatorTitle = null; /* Methods */ /** * Set the indicator element. * * If an element is already set, it will be cleaned up before setting up the new element. * * @param {jQuery} $indicator Element to use as indicator */ OO.ui.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) { if ( this.$indicator ) { this.$indicator .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator ) .removeAttr( 'title' ); } this.$indicator = $indicator .addClass( 'oo-ui-indicatorElement-indicator' ) .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator ); if ( this.indicatorTitle !== null ) { this.$indicator.attr( 'title', this.indicatorTitle ); } }; /** * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator. * * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator * @chainable */ OO.ui.IndicatorElement.prototype.setIndicator = function ( indicator ) { indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null; if ( this.indicator !== indicator ) { if ( this.$indicator ) { if ( this.indicator !== null ) { this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator ); } if ( indicator !== null ) { this.$indicator.addClass( 'oo-ui-indicator-' + indicator ); } } this.indicator = indicator; } this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator ); this.updateThemeClasses(); return this; }; /** * Set the indicator title. * * The title is displayed when a user moves the mouse over the indicator. * * @param {string|Function|null} indicator Indicator title text, a function that returns text, or * `null` for no indicator title * @chainable */ OO.ui.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) { indicatorTitle = typeof indicatorTitle === 'function' || ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ? OO.ui.resolveMsg( indicatorTitle ) : null; if ( this.indicatorTitle !== indicatorTitle ) { this.indicatorTitle = indicatorTitle; if ( this.$indicator ) { if ( this.indicatorTitle !== null ) { this.$indicator.attr( 'title', indicatorTitle ); } else { this.$indicator.removeAttr( 'title' ); } } } return this; }; /** * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’). * * @return {string} Symbolic name of indicator */ OO.ui.IndicatorElement.prototype.getIndicator = function () { return this.indicator; }; /** * Get the indicator title. * * The title is displayed when a user moves the mouse over the indicator. * * @return {string} Indicator title text */ OO.ui.IndicatorElement.prototype.getIndicatorTitle = function () { return this.indicatorTitle; }; /** * LabelElement is often mixed into other classes to generate a label, which * helps identify the function of an interface element. * See the [OOjs UI documentation on MediaWiki] [1] for more information. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$label] The label element created by the class. If this * configuration is omitted, the label element will use a generated `<span>`. * @cfg {jQuery|string|Function} [label] The label text. The label can be specified as a plaintext string, * a jQuery selection of elements, or a function that will produce a string in the future. See the * [OOjs UI documentation on MediaWiki] [2] for examples. * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element. * The label will be truncated to fit if necessary. */ OO.ui.LabelElement = function OoUiLabelElement( config ) { // Configuration initialization config = config || {}; // Properties this.$label = null; this.label = null; this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel; // Initialization this.setLabel( config.label || this.constructor.static.label ); this.setLabelElement( config.$label || $( '<span>' ) ); }; /* Setup */ OO.initClass( OO.ui.LabelElement ); /* Events */ /** * @event labelChange * @param {string} value */ /* Static Properties */ /** * The label text. The label can be specified as a plaintext string, a function that will * produce a string in the future, or `null` for no label. The static value will * be overridden if a label is specified with the #label config option. * * @static * @inheritable * @property {string|Function|null} */ OO.ui.LabelElement.static.label = null; /* Methods */ /** * Set the label element. * * If an element is already set, it will be cleaned up before setting up the new element. * * @param {jQuery} $label Element to use as label */ OO.ui.LabelElement.prototype.setLabelElement = function ( $label ) { if ( this.$label ) { this.$label.removeClass( 'oo-ui-labelElement-label' ).empty(); } this.$label = $label.addClass( 'oo-ui-labelElement-label' ); this.setLabelContent( this.label ); }; /** * Set the label. * * An empty string will result in the label being hidden. A string containing only whitespace will * be converted to a single `&nbsp;`. * * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or * text; or null for no label * @chainable */ OO.ui.LabelElement.prototype.setLabel = function ( label ) { label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label; label = ( ( typeof label === 'string' && label.length ) || label instanceof jQuery || label instanceof OO.ui.HtmlSnippet ) ? label : null; this.$element.toggleClass( 'oo-ui-labelElement', !!label ); if ( this.label !== label ) { if ( this.$label ) { this.setLabelContent( label ); } this.label = label; this.emit( 'labelChange' ); } return this; }; /** * Get the label. * * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or * text; or null for no label */ OO.ui.LabelElement.prototype.getLabel = function () { return this.label; }; /** * Fit the label. * * @chainable */ OO.ui.LabelElement.prototype.fitLabel = function () { if ( this.$label && this.$label.autoEllipsis && this.autoFitLabel ) { this.$label.autoEllipsis( { hasSpan: false, tooltip: true } ); } return this; }; /** * Set the content of the label. * * Do not call this method until after the label element has been set by #setLabelElement. * * @private * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or * text; or null for no label */ OO.ui.LabelElement.prototype.setLabelContent = function ( label ) { if ( typeof label === 'string' ) { if ( label.match( /^\s*$/ ) ) { // Convert whitespace only string to a single non-breaking space this.$label.html( '&nbsp;' ); } else { this.$label.text( label ); } } else if ( label instanceof OO.ui.HtmlSnippet ) { this.$label.html( label.toString() ); } else if ( label instanceof jQuery ) { this.$label.empty().append( label ); } else { this.$label.empty(); } }; /** * LookupElement is a mixin that creates a {@link OO.ui.TextInputMenuSelectWidget menu} of suggested values for * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen * from the lookup menu, that value becomes the value of the input field. * * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then * re-enable lookups. * * See the [OOjs UI demos][1] for an example. * * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr * * @class * @abstract * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element. * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty. * By default, the lookup menu is not generated and displayed until the user begins to type. */ OO.ui.LookupElement = function OoUiLookupElement( config ) { // Configuration initialization config = config || {}; // Properties this.$overlay = config.$overlay || this.$element; this.lookupMenu = new OO.ui.TextInputMenuSelectWidget( this, { widget: this, input: this, $container: config.$container } ); this.allowSuggestionsWhenEmpty = config.allowSuggestionsWhenEmpty || false; this.lookupCache = {}; this.lookupQuery = null; this.lookupRequest = null; this.lookupsDisabled = false; this.lookupInputFocused = false; // Events this.$input.on( { focus: this.onLookupInputFocus.bind( this ), blur: this.onLookupInputBlur.bind( this ), mousedown: this.onLookupInputMouseDown.bind( this ) } ); this.connect( this, { change: 'onLookupInputChange' } ); this.lookupMenu.connect( this, { toggle: 'onLookupMenuToggle', choose: 'onLookupMenuItemChoose' } ); // Initialization this.$element.addClass( 'oo-ui-lookupElement' ); this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' ); this.$overlay.append( this.lookupMenu.$element ); }; /* Methods */ /** * Handle input focus event. * * @protected * @param {jQuery.Event} e Input focus event */ OO.ui.LookupElement.prototype.onLookupInputFocus = function () { this.lookupInputFocused = true; this.populateLookupMenu(); }; /** * Handle input blur event. * * @protected * @param {jQuery.Event} e Input blur event */ OO.ui.LookupElement.prototype.onLookupInputBlur = function () { this.closeLookupMenu(); this.lookupInputFocused = false; }; /** * Handle input mouse down event. * * @protected * @param {jQuery.Event} e Input mouse down event */ OO.ui.LookupElement.prototype.onLookupInputMouseDown = function () { // Only open the menu if the input was already focused. // This way we allow the user to open the menu again after closing it with Esc // by clicking in the input. Opening (and populating) the menu when initially // clicking into the input is handled by the focus handler. if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) { this.populateLookupMenu(); } }; /** * Handle input change event. * * @protected * @param {string} value New input value */ OO.ui.LookupElement.prototype.onLookupInputChange = function () { if ( this.lookupInputFocused ) { this.populateLookupMenu(); } }; /** * Handle the lookup menu being shown/hidden. * * @protected * @param {boolean} visible Whether the lookup menu is now visible. */ OO.ui.LookupElement.prototype.onLookupMenuToggle = function ( visible ) { if ( !visible ) { // When the menu is hidden, abort any active request and clear the menu. // This has to be done here in addition to closeLookupMenu(), because // MenuSelectWidget will close itself when the user presses Esc. this.abortLookupRequest(); this.lookupMenu.clearItems(); } }; /** * Handle menu item 'choose' event, updating the text input value to the value of the clicked item. * * @protected * @param {OO.ui.MenuOptionWidget|null} item Selected item */ OO.ui.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) { if ( item ) { this.setValue( item.getData() ); } }; /** * Get lookup menu. * * @private * @return {OO.ui.TextInputMenuSelectWidget} */ OO.ui.LookupElement.prototype.getLookupMenu = function () { return this.lookupMenu; }; /** * Disable or re-enable lookups. * * When lookups are disabled, calls to #populateLookupMenu will be ignored. * * @param {boolean} disabled Disable lookups */ OO.ui.LookupElement.prototype.setLookupsDisabled = function ( disabled ) { this.lookupsDisabled = !!disabled; }; /** * Open the menu. If there are no entries in the menu, this does nothing. * * @private * @chainable */ OO.ui.LookupElement.prototype.openLookupMenu = function () { if ( !this.lookupMenu.isEmpty() ) { this.lookupMenu.toggle( true ); } return this; }; /** * Close the menu, empty it, and abort any pending request. * * @private * @chainable */ OO.ui.LookupElement.prototype.closeLookupMenu = function () { this.lookupMenu.toggle( false ); this.abortLookupRequest(); this.lookupMenu.clearItems(); return this; }; /** * Request menu items based on the input's current value, and when they arrive, * populate the menu with these items and show the menu. * * If lookups have been disabled with #setLookupsDisabled, this function does nothing. * * @private * @chainable */ OO.ui.LookupElement.prototype.populateLookupMenu = function () { var widget = this, value = this.getValue(); if ( this.lookupsDisabled ) { return; } // If the input is empty, clear the menu, unless suggestions when empty are allowed. if ( !this.allowSuggestionsWhenEmpty && value === '' ) { this.closeLookupMenu(); // Skip population if there is already a request pending for the current value } else if ( value !== this.lookupQuery ) { this.getLookupMenuItems() .done( function ( items ) { widget.lookupMenu.clearItems(); if ( items.length ) { widget.lookupMenu .addItems( items ) .toggle( true ); widget.initializeLookupMenuSelection(); } else { widget.lookupMenu.toggle( false ); } } ) .fail( function () { widget.lookupMenu.clearItems(); } ); } return this; }; /** * Select and highlight the first selectable item in the menu. * * @private * @chainable */ OO.ui.LookupElement.prototype.initializeLookupMenuSelection = function () { if ( !this.lookupMenu.getSelectedItem() ) { this.lookupMenu.selectItem( this.lookupMenu.getFirstSelectableItem() ); } this.lookupMenu.highlightItem( this.lookupMenu.getSelectedItem() ); }; /** * Get lookup menu items for the current query. * * @private * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of * the done event. If the request was aborted to make way for a subsequent request, this promise * will not be rejected: it will remain pending forever. */ OO.ui.LookupElement.prototype.getLookupMenuItems = function () { var widget = this, value = this.getValue(), deferred = $.Deferred(), ourRequest; this.abortLookupRequest(); if ( Object.prototype.hasOwnProperty.call( this.lookupCache, value ) ) { deferred.resolve( this.getLookupMenuOptionsFromData( this.lookupCache[ value ] ) ); } else { this.pushPending(); this.lookupQuery = value; ourRequest = this.lookupRequest = this.getLookupRequest(); ourRequest .always( function () { // We need to pop pending even if this is an old request, otherwise // the widget will remain pending forever. // TODO: this assumes that an aborted request will fail or succeed soon after // being aborted, or at least eventually. It would be nice if we could popPending() // at abort time, but only if we knew that we hadn't already called popPending() // for that request. widget.popPending(); } ) .done( function ( response ) { // If this is an old request (and aborting it somehow caused it to still succeed), // ignore its success completely if ( ourRequest === widget.lookupRequest ) { widget.lookupQuery = null; widget.lookupRequest = null; widget.lookupCache[ value ] = widget.getLookupCacheDataFromResponse( response ); deferred.resolve( widget.getLookupMenuOptionsFromData( widget.lookupCache[ value ] ) ); } } ) .fail( function () { // If this is an old request (or a request failing because it's being aborted), // ignore its failure completely if ( ourRequest === widget.lookupRequest ) { widget.lookupQuery = null; widget.lookupRequest = null; deferred.reject(); } } ); } return deferred.promise(); }; /** * Abort the currently pending lookup request, if any. * * @private */ OO.ui.LookupElement.prototype.abortLookupRequest = function () { var oldRequest = this.lookupRequest; if ( oldRequest ) { // First unset this.lookupRequest to the fail handler will notice // that the request is no longer current this.lookupRequest = null; this.lookupQuery = null; oldRequest.abort(); } }; /** * Get a new request object of the current lookup query value. * * @protected * @abstract * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method */ OO.ui.LookupElement.prototype.getLookupRequest = function () { // Stub, implemented in subclass return null; }; /** * Pre-process data returned by the request from #getLookupRequest. * * The return value of this function will be cached, and any further queries for the given value * will use the cache rather than doing API requests. * * @protected * @abstract * @param {Mixed} response Response from server * @return {Mixed} Cached result data */ OO.ui.LookupElement.prototype.getLookupCacheDataFromResponse = function () { // Stub, implemented in subclass return []; }; /** * Get a list of menu option widgets from the (possibly cached) data returned by * #getLookupCacheDataFromResponse. * * @protected * @abstract * @param {Mixed} data Cached result data, usually an array * @return {OO.ui.MenuOptionWidget[]} Menu items */ OO.ui.LookupElement.prototype.getLookupMenuOptionsFromData = function () { // Stub, implemented in subclass return []; }; /** * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}. * A popup is a container for content. It is overlaid and positioned absolutely. By default, each * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin. * See {@link OO.ui.PopupWidget PopupWidget} for an example. * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {Object} [popup] Configuration to pass to popup * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus */ OO.ui.PopupElement = function OoUiPopupElement( config ) { // Configuration initialization config = config || {}; // Properties this.popup = new OO.ui.PopupWidget( $.extend( { autoClose: true }, config.popup, { $autoCloseIgnore: this.$element } ) ); }; /* Methods */ /** * Get popup. * * @return {OO.ui.PopupWidget} Popup widget */ OO.ui.PopupElement.prototype.getPopup = function () { return this.popup; }; /** * The FlaggedElement class is an attribute mixin, meaning that it is used to add * additional functionality to an element created by another class. The class provides * a ‘flags’ property assigned the name (or an array of names) of styling flags, * which are used to customize the look and feel of a widget to better describe its * importance and functionality. * * The library currently contains the following styling flags for general use: * * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process. * - **destructive**: Destructive styling is applied to convey that the widget will remove something. * - **constructive**: Constructive styling is applied to convey that the widget will create something. * * The flags affect the appearance of the buttons: * * @example * // FlaggedElement is mixed into ButtonWidget to provide styling flags * var button1 = new OO.ui.ButtonWidget( { * label: 'Constructive', * flags: 'constructive' * } ); * var button2 = new OO.ui.ButtonWidget( { * label: 'Destructive', * flags: 'destructive' * } ); * var button3 = new OO.ui.ButtonWidget( { * label: 'Progressive', * flags: 'progressive' * } ); * $( 'body' ).append( button1.$element, button2.$element, button3.$element ); * * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**. * Please see the [OOjs UI documentation on MediaWiki] [1] for more information. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply. * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags. * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged * @cfg {jQuery} [$flagged] The flagged element. By default, * the flagged functionality is applied to the element created by the class ($element). * If a different element is specified, the flagged functionality will be applied to it instead. */ OO.ui.FlaggedElement = function OoUiFlaggedElement( config ) { // Configuration initialization config = config || {}; // Properties this.flags = {}; this.$flagged = null; // Initialization this.setFlags( config.flags ); this.setFlaggedElement( config.$flagged || this.$element ); }; /* Events */ /** * @event flag * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes` * parameter contains the name of each modified flag and indicates whether it was * added or removed. * * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates * that the flag was added, `false` that the flag was removed. */ /* Methods */ /** * Set the flagged element. * * This method is used to retarget a flagged mixin so that its functionality applies to the specified element. * If an element is already set, the method will remove the mixin’s effect on that element. * * @param {jQuery} $flagged Element that should be flagged */ OO.ui.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) { var classNames = Object.keys( this.flags ).map( function ( flag ) { return 'oo-ui-flaggedElement-' + flag; } ).join( ' ' ); if ( this.$flagged ) { this.$flagged.removeClass( classNames ); } this.$flagged = $flagged.addClass( classNames ); }; /** * Check if the specified flag is set. * * @param {string} flag Name of flag * @return {boolean} The flag is set */ OO.ui.FlaggedElement.prototype.hasFlag = function ( flag ) { return flag in this.flags; }; /** * Get the names of all flags set. * * @return {string[]} Flag names */ OO.ui.FlaggedElement.prototype.getFlags = function () { return Object.keys( this.flags ); }; /** * Clear all flags. * * @chainable * @fires flag */ OO.ui.FlaggedElement.prototype.clearFlags = function () { var flag, className, changes = {}, remove = [], classPrefix = 'oo-ui-flaggedElement-'; for ( flag in this.flags ) { className = classPrefix + flag; changes[ flag ] = false; delete this.flags[ flag ]; remove.push( className ); } if ( this.$flagged ) { this.$flagged.removeClass( remove.join( ' ' ) ); } this.updateThemeClasses(); this.emit( 'flag', changes ); return this; }; /** * Add one or more flags. * * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names, * or an object keyed by flag name with a boolean value that indicates whether the flag should * be added (`true`) or removed (`false`). * @chainable * @fires flag */ OO.ui.FlaggedElement.prototype.setFlags = function ( flags ) { var i, len, flag, className, changes = {}, add = [], remove = [], classPrefix = 'oo-ui-flaggedElement-'; if ( typeof flags === 'string' ) { className = classPrefix + flags; // Set if ( !this.flags[ flags ] ) { this.flags[ flags ] = true; add.push( className ); } } else if ( Array.isArray( flags ) ) { for ( i = 0, len = flags.length; i < len; i++ ) { flag = flags[ i ]; className = classPrefix + flag; // Set if ( !this.flags[ flag ] ) { changes[ flag ] = true; this.flags[ flag ] = true; add.push( className ); } } } else if ( OO.isPlainObject( flags ) ) { for ( flag in flags ) { className = classPrefix + flag; if ( flags[ flag ] ) { // Set if ( !this.flags[ flag ] ) { changes[ flag ] = true; this.flags[ flag ] = true; add.push( className ); } } else { // Remove if ( this.flags[ flag ] ) { changes[ flag ] = false; delete this.flags[ flag ]; remove.push( className ); } } } } if ( this.$flagged ) { this.$flagged .addClass( add.join( ' ' ) ) .removeClass( remove.join( ' ' ) ); } this.updateThemeClasses(); this.emit( 'flag', changes ); return this; }; /** * TitledElement is mixed into other classes to provide a `title` attribute. * Titles are rendered by the browser and are made visible when the user moves * the mouse over the element. Titles are not visible on touch devices. * * @example * // TitledElement provides a 'title' attribute to the * // ButtonWidget class * var button = new OO.ui.ButtonWidget( { * label: 'Button with Title', * title: 'I am a button' * } ); * $( 'body' ).append( button.$element ); * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied. * If this config is omitted, the title functionality is applied to $element, the * element created by the class. * @cfg {string|Function} [title] The title text or a function that returns text. If * this config is omitted, the value of the {@link #static-title static title} property is used. */ OO.ui.TitledElement = function OoUiTitledElement( config ) { // Configuration initialization config = config || {}; // Properties this.$titled = null; this.title = null; // Initialization this.setTitle( config.title || this.constructor.static.title ); this.setTitledElement( config.$titled || this.$element ); }; /* Setup */ OO.initClass( OO.ui.TitledElement ); /* Static Properties */ /** * The title text, a function that returns text, or `null` for no title. The value of the static property * is overridden if the #title config option is used. * * @static * @inheritable * @property {string|Function|null} */ OO.ui.TitledElement.static.title = null; /* Methods */ /** * Set the titled element. * * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element. * If an element is already set, the mixin’s effect on that element is removed before the new element is set up. * * @param {jQuery} $titled Element that should use the 'titled' functionality */ OO.ui.TitledElement.prototype.setTitledElement = function ( $titled ) { if ( this.$titled ) { this.$titled.removeAttr( 'title' ); } this.$titled = $titled; if ( this.title ) { this.$titled.attr( 'title', this.title ); } }; /** * Set title. * * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title * @chainable */ OO.ui.TitledElement.prototype.setTitle = function ( title ) { title = typeof title === 'string' ? OO.ui.resolveMsg( title ) : null; if ( this.title !== title ) { if ( this.$titled ) { if ( title !== null ) { this.$titled.attr( 'title', title ); } else { this.$titled.removeAttr( 'title' ); } } this.title = title; } return this; }; /** * Get title. * * @return {string} Title string */ OO.ui.TitledElement.prototype.getTitle = function () { return this.title; }; /** * Element that can be automatically clipped to visible boundaries. * * Whenever the element's natural height changes, you have to call * #clip to make sure it's still clipping correctly. * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$clippable] Nodes to clip, assigned to #$clippable, omit to use #$element */ OO.ui.ClippableElement = function OoUiClippableElement( config ) { // Configuration initialization config = config || {}; // Properties this.$clippable = null; this.clipping = false; this.clippedHorizontally = false; this.clippedVertically = false; this.$clippableContainer = null; this.$clippableScroller = null; this.$clippableWindow = null; this.idealWidth = null; this.idealHeight = null; this.onClippableContainerScrollHandler = this.clip.bind( this ); this.onClippableWindowResizeHandler = this.clip.bind( this ); // Initialization this.setClippableElement( config.$clippable || this.$element ); }; /* Methods */ /** * Set clippable element. * * If an element is already set, it will be cleaned up before setting up the new element. * * @param {jQuery} $clippable Element to make clippable */ OO.ui.ClippableElement.prototype.setClippableElement = function ( $clippable ) { if ( this.$clippable ) { this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' ); this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } ); OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] ); } this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' ); this.clip(); }; /** * Toggle clipping. * * Do not turn clipping on until after the element is attached to the DOM and visible. * * @param {boolean} [clipping] Enable clipping, omit to toggle * @chainable */ OO.ui.ClippableElement.prototype.toggleClipping = function ( clipping ) { clipping = clipping === undefined ? !this.clipping : !!clipping; if ( this.clipping !== clipping ) { this.clipping = clipping; if ( clipping ) { this.$clippableContainer = $( this.getClosestScrollableElementContainer() ); // If the clippable container is the root, we have to listen to scroll events and check // jQuery.scrollTop on the window because of browser inconsistencies this.$clippableScroller = this.$clippableContainer.is( 'html, body' ) ? $( OO.ui.Element.static.getWindow( this.$clippableContainer ) ) : this.$clippableContainer; this.$clippableScroller.on( 'scroll', this.onClippableContainerScrollHandler ); this.$clippableWindow = $( this.getElementWindow() ) .on( 'resize', this.onClippableWindowResizeHandler ); // Initial clip after visible this.clip(); } else { this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } ); OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] ); this.$clippableContainer = null; this.$clippableScroller.off( 'scroll', this.onClippableContainerScrollHandler ); this.$clippableScroller = null; this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler ); this.$clippableWindow = null; } } return this; }; /** * Check if the element will be clipped to fit the visible area of the nearest scrollable container. * * @return {boolean} Element will be clipped to the visible area */ OO.ui.ClippableElement.prototype.isClipping = function () { return this.clipping; }; /** * Check if the bottom or right of the element is being clipped by the nearest scrollable container. * * @return {boolean} Part of the element is being clipped */ OO.ui.ClippableElement.prototype.isClipped = function () { return this.clippedHorizontally || this.clippedVertically; }; /** * Check if the right of the element is being clipped by the nearest scrollable container. * * @return {boolean} Part of the element is being clipped */ OO.ui.ClippableElement.prototype.isClippedHorizontally = function () { return this.clippedHorizontally; }; /** * Check if the bottom of the element is being clipped by the nearest scrollable container. * * @return {boolean} Part of the element is being clipped */ OO.ui.ClippableElement.prototype.isClippedVertically = function () { return this.clippedVertically; }; /** * Set the ideal size. These are the dimensions the element will have when it's not being clipped. * * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix */ OO.ui.ClippableElement.prototype.setIdealSize = function ( width, height ) { this.idealWidth = width; this.idealHeight = height; if ( !this.clipping ) { // Update dimensions this.$clippable.css( { width: width, height: height } ); } // While clipping, idealWidth and idealHeight are not considered }; /** * Clip element to visible boundaries and allow scrolling when needed. Call this method when * the element's natural height changes. * * Element will be clipped the bottom or right of the element is within 10px of the edge of, or * overlapped by, the visible area of the nearest scrollable container. * * @chainable */ OO.ui.ClippableElement.prototype.clip = function () { if ( !this.clipping ) { // this.$clippableContainer and this.$clippableWindow are null, so the below will fail return this; } var buffer = 7, // Chosen by fair dice roll cOffset = this.$clippable.offset(), $container = this.$clippableContainer.is( 'html, body' ) ? this.$clippableWindow : this.$clippableContainer, ccOffset = $container.offset() || { top: 0, left: 0 }, ccHeight = $container.innerHeight() - buffer, ccWidth = $container.innerWidth() - buffer, cHeight = this.$clippable.outerHeight() + buffer, cWidth = this.$clippable.outerWidth() + buffer, scrollTop = this.$clippableScroller.scrollTop(), scrollLeft = this.$clippableScroller.scrollLeft(), desiredWidth = cOffset.left < 0 ? cWidth + cOffset.left : ( ccOffset.left + scrollLeft + ccWidth ) - cOffset.left, desiredHeight = cOffset.top < 0 ? cHeight + cOffset.top : ( ccOffset.top + scrollTop + ccHeight ) - cOffset.top, naturalWidth = this.$clippable.prop( 'scrollWidth' ), naturalHeight = this.$clippable.prop( 'scrollHeight' ), clipWidth = desiredWidth < naturalWidth, clipHeight = desiredHeight < naturalHeight; if ( clipWidth ) { this.$clippable.css( { overflowX: 'scroll', width: desiredWidth } ); } else { this.$clippable.css( { width: this.idealWidth || '', overflowX: '' } ); } if ( clipHeight ) { this.$clippable.css( { overflowY: 'scroll', height: desiredHeight } ); } else { this.$clippable.css( { height: this.idealHeight || '', overflowY: '' } ); } // If we stopped clipping in at least one of the dimensions if ( !clipWidth || !clipHeight ) { OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] ); } this.clippedHorizontally = clipWidth; this.clippedVertically = clipHeight; return this; }; /** * Generic toolbar tool. * * @abstract * @class * @extends OO.ui.Widget * @mixins OO.ui.IconElement * @mixins OO.ui.FlaggedElement * * @constructor * @param {OO.ui.ToolGroup} toolGroup * @param {Object} [config] Configuration options * @cfg {string|Function} [title] Title text or a function that returns text */ OO.ui.Tool = function OoUiTool( toolGroup, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolGroup ) && config === undefined ) { config = toolGroup; toolGroup = config.toolGroup; } // Configuration initialization config = config || {}; // Parent constructor OO.ui.Tool.super.call( this, config ); // Mixin constructors OO.ui.IconElement.call( this, config ); OO.ui.FlaggedElement.call( this, config ); // Properties this.toolGroup = toolGroup; this.toolbar = this.toolGroup.getToolbar(); this.active = false; this.$title = $( '<span>' ); this.$accel = $( '<span>' ); this.$link = $( '<a>' ); this.title = null; // Events this.toolbar.connect( this, { updateState: 'onUpdateState' } ); // Initialization this.$title.addClass( 'oo-ui-tool-title' ); this.$accel .addClass( 'oo-ui-tool-accel' ) .prop( { // This may need to be changed if the key names are ever localized, // but for now they are essentially written in English dir: 'ltr', lang: 'en' } ); this.$link .addClass( 'oo-ui-tool-link' ) .append( this.$icon, this.$title, this.$accel ) .prop( 'tabIndex', 0 ) .attr( 'role', 'button' ); this.$element .data( 'oo-ui-tool', this ) .addClass( 'oo-ui-tool ' + 'oo-ui-tool-name-' + this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' ) ) .append( this.$link ); this.setTitle( config.title || this.constructor.static.title ); }; /* Setup */ OO.inheritClass( OO.ui.Tool, OO.ui.Widget ); OO.mixinClass( OO.ui.Tool, OO.ui.IconElement ); OO.mixinClass( OO.ui.Tool, OO.ui.FlaggedElement ); /* Events */ /** * @event select */ /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.Tool.static.tagName = 'span'; /** * Symbolic name of tool. * * @abstract * @static * @inheritable * @property {string} */ OO.ui.Tool.static.name = ''; /** * Tool group. * * @abstract * @static * @inheritable * @property {string} */ OO.ui.Tool.static.group = ''; /** * Tool title. * * Title is used as a tooltip when the tool is part of a bar tool group, or a label when the tool * is part of a list or menu tool group. If a trigger is associated with an action by the same name * as the tool, a description of its keyboard shortcut for the appropriate platform will be * appended to the title if the tool is part of a bar tool group. * * @abstract * @static * @inheritable * @property {string|Function} Title text or a function that returns text */ OO.ui.Tool.static.title = ''; /** * Tool can be automatically added to catch-all groups. * * @static * @inheritable * @property {boolean} */ OO.ui.Tool.static.autoAddToCatchall = true; /** * Tool can be automatically added to named groups. * * @static * @property {boolean} * @inheritable */ OO.ui.Tool.static.autoAddToGroup = true; /** * Check if this tool is compatible with given data. * * @static * @inheritable * @param {Mixed} data Data to check * @return {boolean} Tool can be used with data */ OO.ui.Tool.static.isCompatibleWith = function () { return false; }; /* Methods */ /** * Handle the toolbar state being updated. * * This is an abstract method that must be overridden in a concrete subclass. * * @abstract */ OO.ui.Tool.prototype.onUpdateState = function () { throw new Error( 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor ); }; /** * Handle the tool being selected. * * This is an abstract method that must be overridden in a concrete subclass. * * @abstract */ OO.ui.Tool.prototype.onSelect = function () { throw new Error( 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor ); }; /** * Check if the button is active. * * @return {boolean} Button is active */ OO.ui.Tool.prototype.isActive = function () { return this.active; }; /** * Make the button appear active or inactive. * * @param {boolean} state Make button appear active */ OO.ui.Tool.prototype.setActive = function ( state ) { this.active = !!state; if ( this.active ) { this.$element.addClass( 'oo-ui-tool-active' ); } else { this.$element.removeClass( 'oo-ui-tool-active' ); } }; /** * Get the tool title. * * @param {string|Function} title Title text or a function that returns text * @chainable */ OO.ui.Tool.prototype.setTitle = function ( title ) { this.title = OO.ui.resolveMsg( title ); this.updateTitle(); return this; }; /** * Get the tool title. * * @return {string} Title text */ OO.ui.Tool.prototype.getTitle = function () { return this.title; }; /** * Get the tool's symbolic name. * * @return {string} Symbolic name of tool */ OO.ui.Tool.prototype.getName = function () { return this.constructor.static.name; }; /** * Update the title. */ OO.ui.Tool.prototype.updateTitle = function () { var titleTooltips = this.toolGroup.constructor.static.titleTooltips, accelTooltips = this.toolGroup.constructor.static.accelTooltips, accel = this.toolbar.getToolAccelerator( this.constructor.static.name ), tooltipParts = []; this.$title.text( this.title ); this.$accel.text( accel ); if ( titleTooltips && typeof this.title === 'string' && this.title.length ) { tooltipParts.push( this.title ); } if ( accelTooltips && typeof accel === 'string' && accel.length ) { tooltipParts.push( accel ); } if ( tooltipParts.length ) { this.$link.attr( 'title', tooltipParts.join( ' ' ) ); } else { this.$link.removeAttr( 'title' ); } }; /** * Destroy tool. */ OO.ui.Tool.prototype.destroy = function () { this.toolbar.disconnect( this ); this.$element.remove(); }; /** * Collection of tool groups. * * @class * @extends OO.ui.Element * @mixins OO.EventEmitter * @mixins OO.ui.GroupElement * * @constructor * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating tool groups * @param {Object} [config] Configuration options * @cfg {boolean} [actions] Add an actions section opposite to the tools * @cfg {boolean} [shadow] Add a shadow below the toolbar */ OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolFactory ) && config === undefined ) { config = toolFactory; toolFactory = config.toolFactory; toolGroupFactory = config.toolGroupFactory; } // Configuration initialization config = config || {}; // Parent constructor OO.ui.Toolbar.super.call( this, config ); // Mixin constructors OO.EventEmitter.call( this ); OO.ui.GroupElement.call( this, config ); // Properties this.toolFactory = toolFactory; this.toolGroupFactory = toolGroupFactory; this.groups = []; this.tools = {}; this.$bar = $( '<div>' ); this.$actions = $( '<div>' ); this.initialized = false; this.onWindowResizeHandler = this.onWindowResize.bind( this ); // Events this.$element .add( this.$bar ).add( this.$group ).add( this.$actions ) .on( 'mousedown', this.onPointerDown.bind( this ) ); // Initialization this.$group.addClass( 'oo-ui-toolbar-tools' ); if ( config.actions ) { this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) ); } this.$bar .addClass( 'oo-ui-toolbar-bar' ) .append( this.$group, '<div style="clear:both"></div>' ); if ( config.shadow ) { this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' ); } this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar ); }; /* Setup */ OO.inheritClass( OO.ui.Toolbar, OO.ui.Element ); OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter ); OO.mixinClass( OO.ui.Toolbar, OO.ui.GroupElement ); /* Methods */ /** * Get the tool factory. * * @return {OO.ui.ToolFactory} Tool factory */ OO.ui.Toolbar.prototype.getToolFactory = function () { return this.toolFactory; }; /** * Get the tool group factory. * * @return {OO.Factory} Tool group factory */ OO.ui.Toolbar.prototype.getToolGroupFactory = function () { return this.toolGroupFactory; }; /** * Handles mouse down events. * * @param {jQuery.Event} e Mouse down event */ OO.ui.Toolbar.prototype.onPointerDown = function ( e ) { var $closestWidgetToEvent = $( e.target ).closest( '.oo-ui-widget' ), $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' ); if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[ 0 ] === $closestWidgetToToolbar[ 0 ] ) { return false; } }; /** * Handle window resize event. * * @private * @param {jQuery.Event} e Window resize event */ OO.ui.Toolbar.prototype.onWindowResize = function () { this.$element.toggleClass( 'oo-ui-toolbar-narrow', this.$bar.width() <= this.narrowThreshold ); }; /** * Sets up handles and preloads required information for the toolbar to work. * This must be called after it is attached to a visible document and before doing anything else. */ OO.ui.Toolbar.prototype.initialize = function () { this.initialized = true; this.narrowThreshold = this.$group.width() + this.$actions.width(); $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler ); this.onWindowResize(); }; /** * Setup toolbar. * * Tools can be specified in the following ways: * * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'` * - All tools in a group: `{ group: 'group-name' }` * - All tools: `'*'` - Using this will make the group a list with a "More" label by default * * @param {Object.<string,Array>} groups List of tool group configurations * @param {Array|string} [groups.include] Tools to include * @param {Array|string} [groups.exclude] Tools to exclude * @param {Array|string} [groups.promote] Tools to promote to the beginning * @param {Array|string} [groups.demote] Tools to demote to the end */ OO.ui.Toolbar.prototype.setup = function ( groups ) { var i, len, type, group, items = [], defaultType = 'bar'; // Cleanup previous groups this.reset(); // Build out new groups for ( i = 0, len = groups.length; i < len; i++ ) { group = groups[ i ]; if ( group.include === '*' ) { // Apply defaults to catch-all groups if ( group.type === undefined ) { group.type = 'list'; } if ( group.label === undefined ) { group.label = OO.ui.msg( 'ooui-toolbar-more' ); } } // Check type has been registered type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType; items.push( this.getToolGroupFactory().create( type, this, group ) ); } this.addItems( items ); }; /** * Remove all tools and groups from the toolbar. */ OO.ui.Toolbar.prototype.reset = function () { var i, len; this.groups = []; this.tools = {}; for ( i = 0, len = this.items.length; i < len; i++ ) { this.items[ i ].destroy(); } this.clearItems(); }; /** * Destroys toolbar, removing event handlers and DOM elements. * * Call this whenever you are done using a toolbar. */ OO.ui.Toolbar.prototype.destroy = function () { $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler ); this.reset(); this.$element.remove(); }; /** * Check if tool has not been used yet. * * @param {string} name Symbolic name of tool * @return {boolean} Tool is available */ OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) { return !this.tools[ name ]; }; /** * Prevent tool from being used again. * * @param {OO.ui.Tool} tool Tool to reserve */ OO.ui.Toolbar.prototype.reserveTool = function ( tool ) { this.tools[ tool.getName() ] = tool; }; /** * Allow tool to be used again. * * @param {OO.ui.Tool} tool Tool to release */ OO.ui.Toolbar.prototype.releaseTool = function ( tool ) { delete this.tools[ tool.getName() ]; }; /** * Get accelerator label for tool. * * This is a stub that should be overridden to provide access to accelerator information. * * @param {string} name Symbolic name of tool * @return {string|undefined} Tool accelerator label if available */ OO.ui.Toolbar.prototype.getToolAccelerator = function () { return undefined; }; /** * Collection of tools. * * Tools can be specified in the following ways: * * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'` * - All tools in a group: `{ group: 'group-name' }` * - All tools: `'*'` * * @abstract * @class * @extends OO.ui.Widget * @mixins OO.ui.GroupElement * * @constructor * @param {OO.ui.Toolbar} toolbar * @param {Object} [config] Configuration options * @cfg {Array|string} [include=[]] List of tools to include * @cfg {Array|string} [exclude=[]] List of tools to exclude * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning * @cfg {Array|string} [demote=[]] List of tools to demote to the end */ OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolbar ) && config === undefined ) { config = toolbar; toolbar = config.toolbar; } // Configuration initialization config = config || {}; // Parent constructor OO.ui.ToolGroup.super.call( this, config ); // Mixin constructors OO.ui.GroupElement.call( this, config ); // Properties this.toolbar = toolbar; this.tools = {}; this.pressed = null; this.autoDisabled = false; this.include = config.include || []; this.exclude = config.exclude || []; this.promote = config.promote || []; this.demote = config.demote || []; this.onCapturedMouseUpHandler = this.onCapturedMouseUp.bind( this ); // Events this.$element.on( { mousedown: this.onPointerDown.bind( this ), mouseup: this.onPointerUp.bind( this ), mouseover: this.onMouseOver.bind( this ), mouseout: this.onMouseOut.bind( this ) } ); this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } ); this.aggregate( { disable: 'itemDisable' } ); this.connect( this, { itemDisable: 'updateDisabled' } ); // Initialization this.$group.addClass( 'oo-ui-toolGroup-tools' ); this.$element .addClass( 'oo-ui-toolGroup' ) .append( this.$group ); this.populate(); }; /* Setup */ OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget ); OO.mixinClass( OO.ui.ToolGroup, OO.ui.GroupElement ); /* Events */ /** * @event update */ /* Static Properties */ /** * Show labels in tooltips. * * @static * @inheritable * @property {boolean} */ OO.ui.ToolGroup.static.titleTooltips = false; /** * Show acceleration labels in tooltips. * * @static * @inheritable * @property {boolean} */ OO.ui.ToolGroup.static.accelTooltips = false; /** * Automatically disable the toolgroup when all tools are disabled * * @static * @inheritable * @property {boolean} */ OO.ui.ToolGroup.static.autoDisable = true; /* Methods */ /** * @inheritdoc */ OO.ui.ToolGroup.prototype.isDisabled = function () { return this.autoDisabled || OO.ui.ToolGroup.super.prototype.isDisabled.apply( this, arguments ); }; /** * @inheritdoc */ OO.ui.ToolGroup.prototype.updateDisabled = function () { var i, item, allDisabled = true; if ( this.constructor.static.autoDisable ) { for ( i = this.items.length - 1; i >= 0; i-- ) { item = this.items[ i ]; if ( !item.isDisabled() ) { allDisabled = false; break; } } this.autoDisabled = allDisabled; } OO.ui.ToolGroup.super.prototype.updateDisabled.apply( this, arguments ); }; /** * Handle mouse down events. * * @param {jQuery.Event} e Mouse down event */ OO.ui.ToolGroup.prototype.onPointerDown = function ( e ) { if ( !this.isDisabled() && e.which === 1 ) { this.pressed = this.getTargetTool( e ); if ( this.pressed ) { this.pressed.setActive( true ); this.getElementDocument().addEventListener( 'mouseup', this.onCapturedMouseUpHandler, true ); } } return false; }; /** * Handle captured mouse up events. * * @param {Event} e Mouse up event */ OO.ui.ToolGroup.prototype.onCapturedMouseUp = function ( e ) { this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseUpHandler, true ); // onPointerUp may be called a second time, depending on where the mouse is when the button is // released, but since `this.pressed` will no longer be true, the second call will be ignored. this.onPointerUp( e ); }; /** * Handle mouse up events. * * @param {jQuery.Event} e Mouse up event */ OO.ui.ToolGroup.prototype.onPointerUp = function ( e ) { var tool = this.getTargetTool( e ); if ( !this.isDisabled() && e.which === 1 && this.pressed && this.pressed === tool ) { this.pressed.onSelect(); } this.pressed = null; return false; }; /** * Handle mouse over events. * * @param {jQuery.Event} e Mouse over event */ OO.ui.ToolGroup.prototype.onMouseOver = function ( e ) { var tool = this.getTargetTool( e ); if ( this.pressed && this.pressed === tool ) { this.pressed.setActive( true ); } }; /** * Handle mouse out events. * * @param {jQuery.Event} e Mouse out event */ OO.ui.ToolGroup.prototype.onMouseOut = function ( e ) { var tool = this.getTargetTool( e ); if ( this.pressed && this.pressed === tool ) { this.pressed.setActive( false ); } }; /** * Get the closest tool to a jQuery.Event. * * Only tool links are considered, which prevents other elements in the tool such as popups from * triggering tool group interactions. * * @private * @param {jQuery.Event} e * @return {OO.ui.Tool|null} Tool, `null` if none was found */ OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) { var tool, $item = $( e.target ).closest( '.oo-ui-tool-link' ); if ( $item.length ) { tool = $item.parent().data( 'oo-ui-tool' ); } return tool && !tool.isDisabled() ? tool : null; }; /** * Handle tool registry register events. * * If a tool is registered after the group is created, we must repopulate the list to account for: * * - a tool being added that may be included * - a tool already included being overridden * * @param {string} name Symbolic name of tool */ OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () { this.populate(); }; /** * Get the toolbar this group is in. * * @return {OO.ui.Toolbar} Toolbar of group */ OO.ui.ToolGroup.prototype.getToolbar = function () { return this.toolbar; }; /** * Add and remove tools based on configuration. */ OO.ui.ToolGroup.prototype.populate = function () { var i, len, name, tool, toolFactory = this.toolbar.getToolFactory(), names = {}, add = [], remove = [], list = this.toolbar.getToolFactory().getTools( this.include, this.exclude, this.promote, this.demote ); // Build a list of needed tools for ( i = 0, len = list.length; i < len; i++ ) { name = list[ i ]; if ( // Tool exists toolFactory.lookup( name ) && // Tool is available or is already in this group ( this.toolbar.isToolAvailable( name ) || this.tools[ name ] ) ) { // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before // creating it, but we can't call reserveTool() yet because we haven't created the tool. this.toolbar.tools[ name ] = true; tool = this.tools[ name ]; if ( !tool ) { // Auto-initialize tools on first use this.tools[ name ] = tool = toolFactory.create( name, this ); tool.updateTitle(); } this.toolbar.reserveTool( tool ); add.push( tool ); names[ name ] = true; } } // Remove tools that are no longer needed for ( name in this.tools ) { if ( !names[ name ] ) { this.tools[ name ].destroy(); this.toolbar.releaseTool( this.tools[ name ] ); remove.push( this.tools[ name ] ); delete this.tools[ name ]; } } if ( remove.length ) { this.removeItems( remove ); } // Update emptiness state if ( add.length ) { this.$element.removeClass( 'oo-ui-toolGroup-empty' ); } else { this.$element.addClass( 'oo-ui-toolGroup-empty' ); } // Re-add tools (moving existing ones to new locations) this.addItems( add ); // Disabled state may depend on items this.updateDisabled(); }; /** * Destroy tool group. */ OO.ui.ToolGroup.prototype.destroy = function () { var name; this.clearItems(); this.toolbar.getToolFactory().disconnect( this ); for ( name in this.tools ) { this.toolbar.releaseTool( this.tools[ name ] ); this.tools[ name ].disconnect( this ).destroy(); delete this.tools[ name ]; } this.$element.remove(); }; /** * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box * consists of a header that contains the dialog title, a body with the message, and a footer that * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type * of {@link OO.ui.Dialog dialog} that is usually instantiated directly. * * There are two basic types of message dialogs, confirmation and alert: * * - **confirmation**: the dialog title describes what a progressive action will do and the message provides * more details about the consequences. * - **alert**: the dialog title describes which event occurred and the message provides more information * about why the event occurred. * * The MessageDialog class specifies two actions: ‘accept’, the primary * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window, * passing along the selected action. * * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1]. * * @example * // Example: Creating and opening a message dialog window. * var messageDialog = new OO.ui.MessageDialog(); * * // Create and append a window manager. * var windowManager = new OO.ui.WindowManager(); * $( 'body' ).append( windowManager.$element ); * windowManager.addWindows( [ messageDialog ] ); * // Open the window. * windowManager.openWindow( messageDialog, { * title: 'Basic message dialog', * message: 'This is the message' * } ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs * * @class * @extends OO.ui.Dialog * * @constructor * @param {Object} [config] Configuration options */ OO.ui.MessageDialog = function OoUiMessageDialog( config ) { // Parent constructor OO.ui.MessageDialog.super.call( this, config ); // Properties this.verticalActionLayout = null; // Initialization this.$element.addClass( 'oo-ui-messageDialog' ); }; /* Inheritance */ OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog ); /* Static Properties */ OO.ui.MessageDialog.static.name = 'message'; OO.ui.MessageDialog.static.size = 'small'; OO.ui.MessageDialog.static.verbose = false; /** * Dialog title. * * The title of a confirmation dialog describes what a progressive action will do. The * title of an alert dialog describes which event occurred. * * @static * @inheritable * @property {jQuery|string|Function|null} */ OO.ui.MessageDialog.static.title = null; /** * The message displayed in the dialog body. * * A confirmation message describes the consequences of a progressive action. An alert * message describes why an event occurred. * * @static * @inheritable * @property {jQuery|string|Function|null} */ OO.ui.MessageDialog.static.message = null; OO.ui.MessageDialog.static.actions = [ { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' }, { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' } ]; /* Methods */ /** * @inheritdoc */ OO.ui.MessageDialog.prototype.setManager = function ( manager ) { OO.ui.MessageDialog.super.prototype.setManager.call( this, manager ); // Events this.manager.connect( this, { resize: 'onResize' } ); return this; }; /** * @inheritdoc */ OO.ui.MessageDialog.prototype.onActionResize = function ( action ) { this.fitActions(); return OO.ui.MessageDialog.super.prototype.onActionResize.call( this, action ); }; /** * Handle window resized events. * * @private */ OO.ui.MessageDialog.prototype.onResize = function () { var dialog = this; dialog.fitActions(); // Wait for CSS transition to finish and do it again :( setTimeout( function () { dialog.fitActions(); }, 300 ); }; /** * Toggle action layout between vertical and horizontal. * * * @private * @param {boolean} [value] Layout actions vertically, omit to toggle * @chainable */ OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) { value = value === undefined ? !this.verticalActionLayout : !!value; if ( value !== this.verticalActionLayout ) { this.verticalActionLayout = value; this.$actions .toggleClass( 'oo-ui-messageDialog-actions-vertical', value ) .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value ); } return this; }; /** * @inheritdoc */ OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) { if ( action ) { return new OO.ui.Process( function () { this.close( { action: action } ); }, this ); } return OO.ui.MessageDialog.super.prototype.getActionProcess.call( this, action ); }; /** * @inheritdoc * * @param {Object} [data] Dialog opening data * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each * action item */ OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) { data = data || {}; // Parent method return OO.ui.MessageDialog.super.prototype.getSetupProcess.call( this, data ) .next( function () { this.title.setLabel( data.title !== undefined ? data.title : this.constructor.static.title ); this.message.setLabel( data.message !== undefined ? data.message : this.constructor.static.message ); this.message.$element.toggleClass( 'oo-ui-messageDialog-message-verbose', data.verbose !== undefined ? data.verbose : this.constructor.static.verbose ); }, this ); }; /** * @inheritdoc */ OO.ui.MessageDialog.prototype.getBodyHeight = function () { var bodyHeight, oldOverflow, $scrollable = this.container.$element; oldOverflow = $scrollable[ 0 ].style.overflow; $scrollable[ 0 ].style.overflow = 'hidden'; OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] ); bodyHeight = this.text.$element.outerHeight( true ); $scrollable[ 0 ].style.overflow = oldOverflow; return bodyHeight; }; /** * @inheritdoc */ OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) { var $scrollable = this.container.$element; OO.ui.MessageDialog.super.prototype.setDimensions.call( this, dim ); // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced. // Need to do it after transition completes (250ms), add 50ms just in case. setTimeout( function () { var oldOverflow = $scrollable[ 0 ].style.overflow; $scrollable[ 0 ].style.overflow = 'hidden'; OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] ); $scrollable[ 0 ].style.overflow = oldOverflow; }, 300 ); return this; }; /** * @inheritdoc */ OO.ui.MessageDialog.prototype.initialize = function () { // Parent method OO.ui.MessageDialog.super.prototype.initialize.call( this ); // Properties this.$actions = $( '<div>' ); this.container = new OO.ui.PanelLayout( { scrollable: true, classes: [ 'oo-ui-messageDialog-container' ] } ); this.text = new OO.ui.PanelLayout( { padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ] } ); this.message = new OO.ui.LabelWidget( { classes: [ 'oo-ui-messageDialog-message' ] } ); // Initialization this.title.$element.addClass( 'oo-ui-messageDialog-title' ); this.$content.addClass( 'oo-ui-messageDialog-content' ); this.container.$element.append( this.text.$element ); this.text.$element.append( this.title.$element, this.message.$element ); this.$body.append( this.container.$element ); this.$actions.addClass( 'oo-ui-messageDialog-actions' ); this.$foot.append( this.$actions ); }; /** * @inheritdoc */ OO.ui.MessageDialog.prototype.attachActions = function () { var i, len, other, special, others; // Parent method OO.ui.MessageDialog.super.prototype.attachActions.call( this ); special = this.actions.getSpecial(); others = this.actions.getOthers(); if ( special.safe ) { this.$actions.append( special.safe.$element ); special.safe.toggleFramed( false ); } if ( others.length ) { for ( i = 0, len = others.length; i < len; i++ ) { other = others[ i ]; this.$actions.append( other.$element ); other.toggleFramed( false ); } } if ( special.primary ) { this.$actions.append( special.primary.$element ); special.primary.toggleFramed( false ); } if ( !this.isOpening() ) { // If the dialog is currently opening, this will be called automatically soon. // This also calls #fitActions. this.updateSize(); } }; /** * Fit action actions into columns or rows. * * Columns will be used if all labels can fit without overflow, otherwise rows will be used. * * @private */ OO.ui.MessageDialog.prototype.fitActions = function () { var i, len, action, previous = this.verticalActionLayout, actions = this.actions.get(); // Detect clipping this.toggleVerticalActionLayout( false ); for ( i = 0, len = actions.length; i < len; i++ ) { action = actions[ i ]; if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) { this.toggleVerticalActionLayout( true ); break; } } // Move the body out of the way of the foot this.$body.css( 'bottom', this.$foot.outerHeight( true ) ); if ( this.verticalActionLayout !== previous ) { // We changed the layout, window height might need to be updated. this.updateSize(); } }; /** * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when * relevant. The ProcessDialog class is always extended and customized with the actions and content * required for each process. * * The process dialog box consists of a header that visually represents the ‘working’ state of long * processes with an animation. The header contains the dialog title as well as * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and * a ‘primary’ action on the right (e.g., ‘Done’). * * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}. * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples. * * @example * // Example: Creating and opening a process dialog window. * function MyProcessDialog( config ) { * MyProcessDialog.super.call( this, config ); * } * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog ); * * MyProcessDialog.static.title = 'Process dialog'; * MyProcessDialog.static.actions = [ * { action: 'save', label: 'Done', flags: 'primary' }, * { label: 'Cancel', flags: 'safe' } * ]; * * MyProcessDialog.prototype.initialize = function () { * MyProcessDialog.super.prototype.initialize.apply( this, arguments ); * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true, expanded: false } ); * this.content.$element.append( '<p>This is a process dialog window. The header contains the title and two buttons: \'Cancel\' (a safe action) on the left and \'Done\' (a primary action) on the right.</p>' ); * this.$body.append( this.content.$element ); * }; * MyProcessDialog.prototype.getActionProcess = function ( action ) { * var dialog = this; * if ( action ) { * return new OO.ui.Process( function () { * dialog.close( { action: action } ); * } ); * } * return MyProcessDialog.super.prototype.getActionProcess.call( this, action ); * }; * * var windowManager = new OO.ui.WindowManager(); * $( 'body' ).append( windowManager.$element ); * * var dialog = new MyProcessDialog(); * windowManager.addWindows( [ dialog ] ); * windowManager.openWindow( dialog ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs * * @abstract * @class * @extends OO.ui.Dialog * * @constructor * @param {Object} [config] Configuration options */ OO.ui.ProcessDialog = function OoUiProcessDialog( config ) { // Parent constructor OO.ui.ProcessDialog.super.call( this, config ); // Initialization this.$element.addClass( 'oo-ui-processDialog' ); }; /* Setup */ OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog ); /* Methods */ /** * Handle dismiss button click events. * * Hides errors. * * @private */ OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () { this.hideErrors(); }; /** * Handle retry button click events. * * Hides errors and then tries again. * * @private */ OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () { this.hideErrors(); this.executeAction( this.currentAction ); }; /** * @inheritdoc */ OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) { if ( this.actions.isSpecial( action ) ) { this.fitLabel(); } return OO.ui.ProcessDialog.super.prototype.onActionResize.call( this, action ); }; /** * @inheritdoc */ OO.ui.ProcessDialog.prototype.initialize = function () { // Parent method OO.ui.ProcessDialog.super.prototype.initialize.call( this ); // Properties this.$navigation = $( '<div>' ); this.$location = $( '<div>' ); this.$safeActions = $( '<div>' ); this.$primaryActions = $( '<div>' ); this.$otherActions = $( '<div>' ); this.dismissButton = new OO.ui.ButtonWidget( { label: OO.ui.msg( 'ooui-dialog-process-dismiss' ) } ); this.retryButton = new OO.ui.ButtonWidget(); this.$errors = $( '<div>' ); this.$errorsTitle = $( '<div>' ); // Events this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } ); this.retryButton.connect( this, { click: 'onRetryButtonClick' } ); // Initialization this.title.$element.addClass( 'oo-ui-processDialog-title' ); this.$location .append( this.title.$element ) .addClass( 'oo-ui-processDialog-location' ); this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' ); this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' ); this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' ); this.$errorsTitle .addClass( 'oo-ui-processDialog-errors-title' ) .text( OO.ui.msg( 'ooui-dialog-process-error' ) ); this.$errors .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' ) .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element ); this.$content .addClass( 'oo-ui-processDialog-content' ) .append( this.$errors ); this.$navigation .addClass( 'oo-ui-processDialog-navigation' ) .append( this.$safeActions, this.$location, this.$primaryActions ); this.$head.append( this.$navigation ); this.$foot.append( this.$otherActions ); }; /** * @inheritdoc */ OO.ui.ProcessDialog.prototype.getActionWidgets = function ( actions ) { var i, len, widgets = []; for ( i = 0, len = actions.length; i < len; i++ ) { widgets.push( new OO.ui.ActionWidget( $.extend( { framed: true }, actions[ i ] ) ) ); } return widgets; }; /** * @inheritdoc */ OO.ui.ProcessDialog.prototype.attachActions = function () { var i, len, other, special, others; // Parent method OO.ui.ProcessDialog.super.prototype.attachActions.call( this ); special = this.actions.getSpecial(); others = this.actions.getOthers(); if ( special.primary ) { this.$primaryActions.append( special.primary.$element ); } for ( i = 0, len = others.length; i < len; i++ ) { other = others[ i ]; this.$otherActions.append( other.$element ); } if ( special.safe ) { this.$safeActions.append( special.safe.$element ); } this.fitLabel(); this.$body.css( 'bottom', this.$foot.outerHeight( true ) ); }; /** * @inheritdoc */ OO.ui.ProcessDialog.prototype.executeAction = function ( action ) { var process = this; return OO.ui.ProcessDialog.super.prototype.executeAction.call( this, action ) .fail( function ( errors ) { process.showErrors( errors || [] ); } ); }; /** * Fit label between actions. * * @private * @chainable */ OO.ui.ProcessDialog.prototype.fitLabel = function () { var width = Math.max( this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0, this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0 ); this.$location.css( { paddingLeft: width, paddingRight: width } ); return this; }; /** * Handle errors that occurred during accept or reject processes. * * @private * @param {OO.ui.Error[]} errors Errors to be handled */ OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) { var i, len, $item, actions, items = [], abilities = {}, recoverable = true, warning = false; for ( i = 0, len = errors.length; i < len; i++ ) { if ( !errors[ i ].isRecoverable() ) { recoverable = false; } if ( errors[ i ].isWarning() ) { warning = true; } $item = $( '<div>' ) .addClass( 'oo-ui-processDialog-error' ) .append( errors[ i ].getMessage() ); items.push( $item[ 0 ] ); } this.$errorItems = $( items ); if ( recoverable ) { abilities[this.currentAction] = true; // Copy the flags from the first matching action actions = this.actions.get( { actions: this.currentAction } ); if ( actions.length ) { this.retryButton.clearFlags().setFlags( actions[0].getFlags() ); } } else { abilities[this.currentAction] = false; this.actions.setAbilities( abilities ); } if ( warning ) { this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) ); } else { this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) ); } this.retryButton.toggle( recoverable ); this.$errorsTitle.after( this.$errorItems ); this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 ); }; /** * Hide errors. * * @private */ OO.ui.ProcessDialog.prototype.hideErrors = function () { this.$errors.addClass( 'oo-ui-element-hidden' ); if ( this.$errorItems ) { this.$errorItems.remove(); this.$errorItems = null; } }; /** * @inheritdoc */ OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) { // Parent method return OO.ui.ProcessDialog.super.prototype.getTeardownProcess.call( this, data ) .first( function () { // Make sure to hide errors this.hideErrors(); }, this ); }; /** * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget, * which is a widget that is specified by reference before any optional configuration settings. * * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways: * * - **left**: The label is placed before the field-widget and aligned with the left margin. * A left-alignment is used for forms with many fields. * - **right**: The label is placed before the field-widget and aligned to the right margin. * A right-alignment is used for long but familiar forms which users tab through, * verifying the current field with a quick glance at the label. * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms * that users fill out from top to bottom. * - **inline**: The label is placed after the field-widget and aligned to the left. * An inline-alignment is best used with checkboxes or radio buttons. * * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout. * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets * @class * @extends OO.ui.Layout * @mixins OO.ui.LabelElement * * @constructor * @param {OO.ui.Widget} fieldWidget Field widget * @param {Object} [config] Configuration options * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline' * @cfg {string} [help] Help text. When help text is specified, a help icon will appear * in the upper-right corner of the rendered field. */ OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( fieldWidget ) && config === undefined ) { config = fieldWidget; fieldWidget = config.fieldWidget; } var hasInputWidget = fieldWidget instanceof OO.ui.InputWidget; // Configuration initialization config = $.extend( { align: 'left' }, config ); // Parent constructor OO.ui.FieldLayout.super.call( this, config ); // Mixin constructors OO.ui.LabelElement.call( this, config ); // Properties this.fieldWidget = fieldWidget; this.$field = $( '<div>' ); this.$body = $( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' ); this.align = null; if ( config.help ) { this.popupButtonWidget = new OO.ui.PopupButtonWidget( { classes: [ 'oo-ui-fieldLayout-help' ], framed: false, icon: 'info' } ); this.popupButtonWidget.getPopup().$body.append( $( '<div>' ) .text( config.help ) .addClass( 'oo-ui-fieldLayout-help-content' ) ); this.$help = this.popupButtonWidget.$element; } else { this.$help = $( [] ); } // Events if ( hasInputWidget ) { this.$label.on( 'click', this.onLabelClick.bind( this ) ); } this.fieldWidget.connect( this, { disable: 'onFieldDisable' } ); // Initialization this.$element .addClass( 'oo-ui-fieldLayout' ) .append( this.$help, this.$body ); this.$body.addClass( 'oo-ui-fieldLayout-body' ); this.$field .addClass( 'oo-ui-fieldLayout-field' ) .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget.isDisabled() ) .append( this.fieldWidget.$element ); this.setAlignment( config.align ); }; /* Setup */ OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout ); OO.mixinClass( OO.ui.FieldLayout, OO.ui.LabelElement ); /* Methods */ /** * Handle field disable events. * * @private * @param {boolean} value Field is disabled */ OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) { this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value ); }; /** * Handle label mouse click events. * * @private * @param {jQuery.Event} e Mouse click event */ OO.ui.FieldLayout.prototype.onLabelClick = function () { this.fieldWidget.simulateLabelClick(); return false; }; /** * Get the widget contained by the field. * * @return {OO.ui.Widget} Field widget */ OO.ui.FieldLayout.prototype.getField = function () { return this.fieldWidget; }; /** * Set the field alignment mode. * * @private * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline' * @chainable */ OO.ui.FieldLayout.prototype.setAlignment = function ( value ) { if ( value !== this.align ) { // Default to 'left' if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) { value = 'left'; } // Reorder elements if ( value === 'inline' ) { this.$body.append( this.$field, this.$label ); } else { this.$body.append( this.$label, this.$field ); } // Set classes. The following classes can be used here: // * oo-ui-fieldLayout-align-left // * oo-ui-fieldLayout-align-right // * oo-ui-fieldLayout-align-top // * oo-ui-fieldLayout-align-inline if ( this.align ) { this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align ); } this.$element.addClass( 'oo-ui-fieldLayout-align-' + value ); this.align = value; } return this; }; /** * Layout made of a field, a button, and an optional label. * * @class * @extends OO.ui.FieldLayout * * @constructor * @param {OO.ui.Widget} fieldWidget Field widget * @param {OO.ui.ButtonWidget} buttonWidget Button widget * @param {Object} [config] Configuration options * @cfg {string} [align='left'] Alignment mode, either 'left', 'right', 'top' or 'inline' * @cfg {string} [help] Explanatory text shown as a '?' icon. */ OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( fieldWidget ) && config === undefined ) { config = fieldWidget; fieldWidget = config.fieldWidget; buttonWidget = config.buttonWidget; } // Configuration initialization config = $.extend( { align: 'left' }, config ); // Parent constructor OO.ui.ActionFieldLayout.super.call( this, fieldWidget, config ); // Properties this.fieldWidget = fieldWidget; this.buttonWidget = buttonWidget; this.$button = $( '<div>' ) .addClass( 'oo-ui-actionFieldLayout-button' ) .append( this.buttonWidget.$element ); this.$input = $( '<div>' ) .addClass( 'oo-ui-actionFieldLayout-input' ) .append( this.fieldWidget.$element ); this.$field .addClass( 'oo-ui-actionFieldLayout' ) .append( this.$input, this.$button ); }; /* Setup */ OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout ); /** * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts}, * which each contain an individual widget and, optionally, a label. Each Fieldset can be * configured with a label as well. For more information and examples, * please see the [OOjs UI documentation on MediaWiki][1]. * * @example * // Example of a fieldset layout * var input1 = new OO.ui.TextInputWidget( { * placeholder: 'A text input field' * } ); * * var input2 = new OO.ui.TextInputWidget( { * placeholder: 'A text input field' * } ); * * var fieldset = new OO.ui.FieldsetLayout( { * label: 'Example of a fieldset layout' * } ); * * fieldset.addItems( [ * new OO.ui.FieldLayout( input1, { * label: 'Field One' * } ), * new OO.ui.FieldLayout( input2, { * label: 'Field Two' * } ) * ] ); * $( 'body' ).append( fieldset.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets * * @class * @extends OO.ui.Layout * @mixins OO.ui.IconElement * @mixins OO.ui.LabelElement * @mixins OO.ui.GroupElement * * @constructor * @param {Object} [config] Configuration options * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields. */ OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.FieldsetLayout.super.call( this, config ); // Mixin constructors OO.ui.IconElement.call( this, config ); OO.ui.LabelElement.call( this, config ); OO.ui.GroupElement.call( this, config ); if ( config.help ) { this.popupButtonWidget = new OO.ui.PopupButtonWidget( { classes: [ 'oo-ui-fieldsetLayout-help' ], framed: false, icon: 'info' } ); this.popupButtonWidget.getPopup().$body.append( $( '<div>' ) .text( config.help ) .addClass( 'oo-ui-fieldsetLayout-help-content' ) ); this.$help = this.popupButtonWidget.$element; } else { this.$help = $( [] ); } // Initialization this.$element .addClass( 'oo-ui-fieldsetLayout' ) .prepend( this.$help, this.$icon, this.$label, this.$group ); if ( Array.isArray( config.items ) ) { this.addItems( config.items ); } }; /* Setup */ OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout ); OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.IconElement ); OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.LabelElement ); OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.GroupElement ); /** * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively. * * @example * // Example of a form layout that wraps a fieldset layout * var input1 = new OO.ui.TextInputWidget( { * placeholder: 'Username' * } ); * var input2 = new OO.ui.TextInputWidget( { * placeholder: 'Password', * type: 'password' * } ); * var submit = new OO.ui.ButtonInputWidget( { * label: 'Submit' * } ); * * var fieldset = new OO.ui.FieldsetLayout( { * label: 'A form layout' * } ); * fieldset.addItems( [ * new OO.ui.FieldLayout( input1, { * label: 'Username', * align: 'top' * } ), * new OO.ui.FieldLayout( input2, { * label: 'Password', * align: 'top' * } ), * new OO.ui.FieldLayout( submit ) * ] ); * var form = new OO.ui.FormLayout( { * items: [ fieldset ], * action: '/api/formhandler', * method: 'get' * } ) * $( 'body' ).append( form.$element ); * * @class * @extends OO.ui.Layout * @mixins OO.ui.GroupElement * * @constructor * @param {Object} [config] Configuration options * @cfg {string} [method] HTML form `method` attribute * @cfg {string} [action] HTML form `action` attribute * @cfg {string} [enctype] HTML form `enctype` attribute * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout. */ OO.ui.FormLayout = function OoUiFormLayout( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.FormLayout.super.call( this, config ); // Mixin constructors OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) ); // Events this.$element.on( 'submit', this.onFormSubmit.bind( this ) ); // Initialization this.$element .addClass( 'oo-ui-formLayout' ) .attr( { method: config.method, action: config.action, enctype: config.enctype } ); if ( Array.isArray( config.items ) ) { this.addItems( config.items ); } }; /* Setup */ OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout ); OO.mixinClass( OO.ui.FormLayout, OO.ui.GroupElement ); /* Events */ /** * A 'submit' event is emitted when the form is submitted. * * @event submit */ /* Static Properties */ OO.ui.FormLayout.static.tagName = 'form'; /* Methods */ /** * Handle form submit events. * * @private * @param {jQuery.Event} e Submit event * @fires submit */ OO.ui.FormLayout.prototype.onFormSubmit = function () { this.emit( 'submit' ); return false; }; /** * Layout with a content and menu area. * * The menu area can be positioned at the top, after, bottom or before. The content area will fill * all remaining space. * * @class * @extends OO.ui.Layout * * @constructor * @param {Object} [config] Configuration options * @cfg {number|string} [menuSize='18em'] Size of menu in pixels or any CSS unit * @cfg {boolean} [showMenu=true] Show menu * @cfg {string} [position='before'] Position of menu, either `top`, `after`, `bottom` or `before` * @cfg {boolean} [collapse] Collapse the menu out of view */ OO.ui.MenuLayout = function OoUiMenuLayout( config ) { var positions = this.constructor.static.menuPositions; // Configuration initialization config = config || {}; // Parent constructor OO.ui.MenuLayout.super.call( this, config ); // Properties this.showMenu = config.showMenu !== false; this.menuSize = config.menuSize || '18em'; this.menuPosition = positions[ config.menuPosition ] || positions.before; /** * Menu DOM node * * @property {jQuery} */ this.$menu = $( '<div>' ); /** * Content DOM node * * @property {jQuery} */ this.$content = $( '<div>' ); // Initialization this.toggleMenu( this.showMenu ); this.updateSizes(); this.$menu .addClass( 'oo-ui-menuLayout-menu' ) .css( this.menuPosition.sizeProperty, this.menuSize ); this.$content.addClass( 'oo-ui-menuLayout-content' ); this.$element .addClass( 'oo-ui-menuLayout ' + this.menuPosition.className ) .append( this.$content, this.$menu ); }; /* Setup */ OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout ); /* Static Properties */ OO.ui.MenuLayout.static.menuPositions = { top: { sizeProperty: 'height', className: 'oo-ui-menuLayout-top' }, after: { sizeProperty: 'width', className: 'oo-ui-menuLayout-after' }, bottom: { sizeProperty: 'height', className: 'oo-ui-menuLayout-bottom' }, before: { sizeProperty: 'width', className: 'oo-ui-menuLayout-before' } }; /* Methods */ /** * Toggle menu. * * @param {boolean} showMenu Show menu, omit to toggle * @chainable */ OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) { showMenu = showMenu === undefined ? !this.showMenu : !!showMenu; if ( this.showMenu !== showMenu ) { this.showMenu = showMenu; this.updateSizes(); } return this; }; /** * Check if menu is visible * * @return {boolean} Menu is visible */ OO.ui.MenuLayout.prototype.isMenuVisible = function () { return this.showMenu; }; /** * Set menu size. * * @param {number|string} size Size of menu in pixels or any CSS unit * @chainable */ OO.ui.MenuLayout.prototype.setMenuSize = function ( size ) { this.menuSize = size; this.updateSizes(); return this; }; /** * Update menu and content CSS based on current menu size and visibility * * This method is called internally when size or position is changed. */ OO.ui.MenuLayout.prototype.updateSizes = function () { if ( this.showMenu ) { this.$menu .css( this.menuPosition.sizeProperty, this.menuSize ) .css( 'overflow', '' ); // Set offsets on all sides. CSS resets all but one with // 'important' rules so directionality flips are supported this.$content.css( { top: this.menuSize, right: this.menuSize, bottom: this.menuSize, left: this.menuSize } ); } else { this.$menu .css( this.menuPosition.sizeProperty, 0 ) .css( 'overflow', 'hidden' ); this.$content.css( { top: 0, right: 0, bottom: 0, left: 0 } ); } }; /** * Get menu size. * * @return {number|string} Menu size */ OO.ui.MenuLayout.prototype.getMenuSize = function () { return this.menuSize; }; /** * Set menu position. * * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before` * @throws {Error} If position value is not supported * @chainable */ OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) { var positions = this.constructor.static.menuPositions; if ( !positions[ position ] ) { throw new Error( 'Cannot set position; unsupported position value: ' + position ); } this.$menu.css( this.menuPosition.sizeProperty, '' ); this.$element.removeClass( this.menuPosition.className ); this.menuPosition = positions[ position ]; this.updateSizes(); this.$element.addClass( this.menuPosition.className ); return this; }; /** * Get menu position. * * @return {string} Menu position */ OO.ui.MenuLayout.prototype.getMenuPosition = function () { return this.menuPosition; }; /** * Layout containing a series of pages. * * @class * @extends OO.ui.MenuLayout * * @constructor * @param {Object} [config] Configuration options * @cfg {boolean} [continuous=false] Show all pages, one after another * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when changing to a page * @cfg {boolean} [outlined=false] Show an outline * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages */ OO.ui.BookletLayout = function OoUiBookletLayout( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.BookletLayout.super.call( this, config ); // Properties this.currentPageName = null; this.pages = {}; this.ignoreFocus = false; this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } ); this.$content.append( this.stackLayout.$element ); this.autoFocus = config.autoFocus === undefined || !!config.autoFocus; this.outlineVisible = false; this.outlined = !!config.outlined; if ( this.outlined ) { this.editable = !!config.editable; this.outlineControlsWidget = null; this.outlineSelectWidget = new OO.ui.OutlineSelectWidget(); this.outlinePanel = new OO.ui.PanelLayout( { scrollable: true } ); this.$menu.append( this.outlinePanel.$element ); this.outlineVisible = true; if ( this.editable ) { this.outlineControlsWidget = new OO.ui.OutlineControlsWidget( this.outlineSelectWidget ); } } this.toggleMenu( this.outlined ); // Events this.stackLayout.connect( this, { set: 'onStackLayoutSet' } ); if ( this.outlined ) { this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } ); } if ( this.autoFocus ) { // Event 'focus' does not bubble, but 'focusin' does this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) ); } // Initialization this.$element.addClass( 'oo-ui-bookletLayout' ); this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' ); if ( this.outlined ) { this.outlinePanel.$element .addClass( 'oo-ui-bookletLayout-outlinePanel' ) .append( this.outlineSelectWidget.$element ); if ( this.editable ) { this.outlinePanel.$element .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' ) .append( this.outlineControlsWidget.$element ); } } }; /* Setup */ OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout ); /* Events */ /** * @event set * @param {OO.ui.PageLayout} page Current page */ /** * @event add * @param {OO.ui.PageLayout[]} page Added pages * @param {number} index Index pages were added at */ /** * @event remove * @param {OO.ui.PageLayout[]} pages Removed pages */ /* Methods */ /** * Handle stack layout focus. * * @param {jQuery.Event} e Focusin event */ OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) { var name, $target; // Find the page that an element was focused within $target = $( e.target ).closest( '.oo-ui-pageLayout' ); for ( name in this.pages ) { // Check for page match, exclude current page to find only page changes if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) { this.setPage( name ); break; } } }; /** * Handle stack layout set events. * * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel */ OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) { var layout = this; if ( page ) { page.scrollElementIntoView( { complete: function () { if ( layout.autoFocus ) { layout.focus(); } } } ); } }; /** * Focus the first input in the current page. * * If no page is selected, the first selectable page will be selected. * If the focus is already in an element on the current page, nothing will happen. */ OO.ui.BookletLayout.prototype.focus = function () { var $input, page = this.stackLayout.getCurrentItem(); if ( !page && this.outlined ) { this.selectFirstSelectablePage(); page = this.stackLayout.getCurrentItem(); } if ( !page ) { return; } // Only change the focus if is not already in the current page if ( !page.$element.find( ':focus' ).length ) { $input = page.$element.find( ':input:first' ); if ( $input.length ) { $input[ 0 ].focus(); } } }; /** * Handle outline widget select events. * * @param {OO.ui.OptionWidget|null} item Selected item */ OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) { if ( item ) { this.setPage( item.getData() ); } }; /** * Check if booklet has an outline. * * @return {boolean} */ OO.ui.BookletLayout.prototype.isOutlined = function () { return this.outlined; }; /** * Check if booklet has editing controls. * * @return {boolean} */ OO.ui.BookletLayout.prototype.isEditable = function () { return this.editable; }; /** * Check if booklet has a visible outline. * * @return {boolean} */ OO.ui.BookletLayout.prototype.isOutlineVisible = function () { return this.outlined && this.outlineVisible; }; /** * Hide or show the outline. * * @param {boolean} [show] Show outline, omit to invert current state * @chainable */ OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) { if ( this.outlined ) { show = show === undefined ? !this.outlineVisible : !!show; this.outlineVisible = show; this.toggleMenu( show ); } return this; }; /** * Get the outline widget. * * @param {OO.ui.PageLayout} page Page to be selected * @return {OO.ui.PageLayout|null} Closest page to another */ OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) { var next, prev, level, pages = this.stackLayout.getItems(), index = $.inArray( page, pages ); if ( index !== -1 ) { next = pages[ index + 1 ]; prev = pages[ index - 1 ]; // Prefer adjacent pages at the same level if ( this.outlined ) { level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel(); if ( prev && level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel() ) { return prev; } if ( next && level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel() ) { return next; } } } return prev || next || null; }; /** * Get the outline widget. * * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if booklet has no outline */ OO.ui.BookletLayout.prototype.getOutline = function () { return this.outlineSelectWidget; }; /** * Get the outline controls widget. If the outline is not editable, null is returned. * * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget. */ OO.ui.BookletLayout.prototype.getOutlineControls = function () { return this.outlineControlsWidget; }; /** * Get a page by name. * * @param {string} name Symbolic name of page * @return {OO.ui.PageLayout|undefined} Page, if found */ OO.ui.BookletLayout.prototype.getPage = function ( name ) { return this.pages[ name ]; }; /** * Get the current page * * @return {OO.ui.PageLayout|undefined} Current page, if found */ OO.ui.BookletLayout.prototype.getCurrentPage = function () { var name = this.getCurrentPageName(); return name ? this.getPage( name ) : undefined; }; /** * Get the current page name. * * @return {string|null} Current page name */ OO.ui.BookletLayout.prototype.getCurrentPageName = function () { return this.currentPageName; }; /** * Add a page to the layout. * * When pages are added with the same names as existing pages, the existing pages will be * automatically removed before the new pages are added. * * @param {OO.ui.PageLayout[]} pages Pages to add * @param {number} index Index to insert pages after * @fires add * @chainable */ OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) { var i, len, name, page, item, currentIndex, stackLayoutPages = this.stackLayout.getItems(), remove = [], items = []; // Remove pages with same names for ( i = 0, len = pages.length; i < len; i++ ) { page = pages[ i ]; name = page.getName(); if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) { // Correct the insertion index currentIndex = $.inArray( this.pages[ name ], stackLayoutPages ); if ( currentIndex !== -1 && currentIndex + 1 < index ) { index--; } remove.push( this.pages[ name ] ); } } if ( remove.length ) { this.removePages( remove ); } // Add new pages for ( i = 0, len = pages.length; i < len; i++ ) { page = pages[ i ]; name = page.getName(); this.pages[ page.getName() ] = page; if ( this.outlined ) { item = new OO.ui.OutlineOptionWidget( { data: name } ); page.setOutlineItem( item ); items.push( item ); } } if ( this.outlined && items.length ) { this.outlineSelectWidget.addItems( items, index ); this.selectFirstSelectablePage(); } this.stackLayout.addItems( pages, index ); this.emit( 'add', pages, index ); return this; }; /** * Remove a page from the layout. * * @fires remove * @chainable */ OO.ui.BookletLayout.prototype.removePages = function ( pages ) { var i, len, name, page, items = []; for ( i = 0, len = pages.length; i < len; i++ ) { page = pages[ i ]; name = page.getName(); delete this.pages[ name ]; if ( this.outlined ) { items.push( this.outlineSelectWidget.getItemFromData( name ) ); page.setOutlineItem( null ); } } if ( this.outlined && items.length ) { this.outlineSelectWidget.removeItems( items ); this.selectFirstSelectablePage(); } this.stackLayout.removeItems( pages ); this.emit( 'remove', pages ); return this; }; /** * Clear all pages from the layout. * * @fires remove * @chainable */ OO.ui.BookletLayout.prototype.clearPages = function () { var i, len, pages = this.stackLayout.getItems(); this.pages = {}; this.currentPageName = null; if ( this.outlined ) { this.outlineSelectWidget.clearItems(); for ( i = 0, len = pages.length; i < len; i++ ) { pages[ i ].setOutlineItem( null ); } } this.stackLayout.clearItems(); this.emit( 'remove', pages ); return this; }; /** * Set the current page by name. * * @fires set * @param {string} name Symbolic name of page */ OO.ui.BookletLayout.prototype.setPage = function ( name ) { var selectedItem, $focused, page = this.pages[ name ]; if ( name !== this.currentPageName ) { if ( this.outlined ) { selectedItem = this.outlineSelectWidget.getSelectedItem(); if ( selectedItem && selectedItem.getData() !== name ) { this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getItemFromData( name ) ); } } if ( page ) { if ( this.currentPageName && this.pages[ this.currentPageName ] ) { this.pages[ this.currentPageName ].setActive( false ); // Blur anything focused if the next page doesn't have anything focusable - this // is not needed if the next page has something focusable because once it is focused // this blur happens automatically if ( this.autoFocus && !page.$element.find( ':input' ).length ) { $focused = this.pages[ this.currentPageName ].$element.find( ':focus' ); if ( $focused.length ) { $focused[ 0 ].blur(); } } } this.currentPageName = name; this.stackLayout.setItem( page ); page.setActive( true ); this.emit( 'set', page ); } } }; /** * Select the first selectable page. * * @chainable */ OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () { if ( !this.outlineSelectWidget.getSelectedItem() ) { this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() ); } return this; }; /** * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding, * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}. * * @example * // Example of a panel layout * var panel = new OO.ui.PanelLayout( { * expanded: false, * framed: true, * padded: true, * $content: $( '<p>A panel layout with padding and a frame.</p>' ) * } ); * $( 'body' ).append( panel.$element ); * * @class * @extends OO.ui.Layout * * @constructor * @param {Object} [config] Configuration options * @cfg {boolean} [scrollable=false] Allow vertical scrolling * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel. * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element. * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content. */ OO.ui.PanelLayout = function OoUiPanelLayout( config ) { // Configuration initialization config = $.extend( { scrollable: false, padded: false, expanded: true, framed: false }, config ); // Parent constructor OO.ui.PanelLayout.super.call( this, config ); // Initialization this.$element.addClass( 'oo-ui-panelLayout' ); if ( config.scrollable ) { this.$element.addClass( 'oo-ui-panelLayout-scrollable' ); } if ( config.padded ) { this.$element.addClass( 'oo-ui-panelLayout-padded' ); } if ( config.expanded ) { this.$element.addClass( 'oo-ui-panelLayout-expanded' ); } if ( config.framed ) { this.$element.addClass( 'oo-ui-panelLayout-framed' ); } }; /* Setup */ OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout ); /** * Page within an booklet layout. * * @class * @extends OO.ui.PanelLayout * * @constructor * @param {string} name Unique symbolic name of page * @param {Object} [config] Configuration options */ OO.ui.PageLayout = function OoUiPageLayout( name, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( name ) && config === undefined ) { config = name; name = config.name; } // Configuration initialization config = $.extend( { scrollable: true }, config ); // Parent constructor OO.ui.PageLayout.super.call( this, config ); // Properties this.name = name; this.outlineItem = null; this.active = false; // Initialization this.$element.addClass( 'oo-ui-pageLayout' ); }; /* Setup */ OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout ); /* Events */ /** * @event active * @param {boolean} active Page is active */ /* Methods */ /** * Get page name. * * @return {string} Symbolic name of page */ OO.ui.PageLayout.prototype.getName = function () { return this.name; }; /** * Check if page is active. * * @return {boolean} Page is active */ OO.ui.PageLayout.prototype.isActive = function () { return this.active; }; /** * Get outline item. * * @return {OO.ui.OutlineOptionWidget|null} Outline item widget */ OO.ui.PageLayout.prototype.getOutlineItem = function () { return this.outlineItem; }; /** * Set outline item. * * @localdoc Subclasses should override #setupOutlineItem instead of this method to adjust the * outline item as desired; this method is called for setting (with an object) and unsetting * (with null) and overriding methods would have to check the value of `outlineItem` to avoid * operating on null instead of an OO.ui.OutlineOptionWidget object. * * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline item widget, null to clear * @chainable */ OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) { this.outlineItem = outlineItem || null; if ( outlineItem ) { this.setupOutlineItem(); } return this; }; /** * Setup outline item. * * @localdoc Subclasses should override this method to adjust the outline item as desired. * * @param {OO.ui.OutlineOptionWidget} outlineItem Outline item widget to setup * @chainable */ OO.ui.PageLayout.prototype.setupOutlineItem = function () { return this; }; /** * Set page active state. * * @param {boolean} Page is active * @fires active */ OO.ui.PageLayout.prototype.setActive = function ( active ) { active = !!active; if ( active !== this.active ) { this.active = active; this.$element.toggleClass( 'oo-ui-pageLayout-active', active ); this.emit( 'active', this.active ); } }; /** * Layout containing a series of mutually exclusive pages. * * @class * @extends OO.ui.PanelLayout * @mixins OO.ui.GroupElement * * @constructor * @param {Object} [config] Configuration options * @cfg {boolean} [continuous=false] Show all pages, one after another * @cfg {OO.ui.Layout[]} [items] Layouts to add */ OO.ui.StackLayout = function OoUiStackLayout( config ) { // Configuration initialization config = $.extend( { scrollable: true }, config ); // Parent constructor OO.ui.StackLayout.super.call( this, config ); // Mixin constructors OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) ); // Properties this.currentItem = null; this.continuous = !!config.continuous; // Initialization this.$element.addClass( 'oo-ui-stackLayout' ); if ( this.continuous ) { this.$element.addClass( 'oo-ui-stackLayout-continuous' ); } if ( Array.isArray( config.items ) ) { this.addItems( config.items ); } }; /* Setup */ OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout ); OO.mixinClass( OO.ui.StackLayout, OO.ui.GroupElement ); /* Events */ /** * @event set * @param {OO.ui.Layout|null} item Current item or null if there is no longer a layout shown */ /* Methods */ /** * Get the current item. * * @return {OO.ui.Layout|null} */ OO.ui.StackLayout.prototype.getCurrentItem = function () { return this.currentItem; }; /** * Unset the current item. * * @private * @param {OO.ui.StackLayout} layout * @fires set */ OO.ui.StackLayout.prototype.unsetCurrentItem = function () { var prevItem = this.currentItem; if ( prevItem === null ) { return; } this.currentItem = null; this.emit( 'set', null ); }; /** * Add items. * * Adding an existing item (by value) will move it. * * @param {OO.ui.Layout[]} items Items to add * @param {number} [index] Index to insert items after * @chainable */ OO.ui.StackLayout.prototype.addItems = function ( items, index ) { // Update the visibility this.updateHiddenState( items, this.currentItem ); // Mixin method OO.ui.GroupElement.prototype.addItems.call( this, items, index ); if ( !this.currentItem && items.length ) { this.setItem( items[ 0 ] ); } return this; }; /** * Remove items. * * Items will be detached, not removed, so they can be used later. * * @param {OO.ui.Layout[]} items Items to remove * @chainable * @fires set */ OO.ui.StackLayout.prototype.removeItems = function ( items ) { // Mixin method OO.ui.GroupElement.prototype.removeItems.call( this, items ); if ( $.inArray( this.currentItem, items ) !== -1 ) { if ( this.items.length ) { this.setItem( this.items[ 0 ] ); } else { this.unsetCurrentItem(); } } return this; }; /** * Clear all items. * * Items will be detached, not removed, so they can be used later. * * @chainable * @fires set */ OO.ui.StackLayout.prototype.clearItems = function () { this.unsetCurrentItem(); OO.ui.GroupElement.prototype.clearItems.call( this ); return this; }; /** * Show item. * * Any currently shown item will be hidden. * * FIXME: If the passed item to show has not been added in the items list, then * this method drops it and unsets the current item. * * @param {OO.ui.Layout} item Item to show * @chainable * @fires set */ OO.ui.StackLayout.prototype.setItem = function ( item ) { if ( item !== this.currentItem ) { this.updateHiddenState( this.items, item ); if ( $.inArray( item, this.items ) !== -1 ) { this.currentItem = item; this.emit( 'set', item ); } else { this.unsetCurrentItem(); } } return this; }; /** * Update the visibility of all items in case of non-continuous view. * * Ensure all items are hidden except for the selected one. * This method does nothing when the stack is continuous. * * @param {OO.ui.Layout[]} items Item list iterate over * @param {OO.ui.Layout} [selectedItem] Selected item to show */ OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) { var i, len; if ( !this.continuous ) { for ( i = 0, len = items.length; i < len; i++ ) { if ( !selectedItem || selectedItem !== items[ i ] ) { items[ i ].$element.addClass( 'oo-ui-element-hidden' ); } } if ( selectedItem ) { selectedItem.$element.removeClass( 'oo-ui-element-hidden' ); } } }; /** * Horizontal bar layout of tools as icon buttons. * * @class * @extends OO.ui.ToolGroup * * @constructor * @param {OO.ui.Toolbar} toolbar * @param {Object} [config] Configuration options */ OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolbar ) && config === undefined ) { config = toolbar; toolbar = config.toolbar; } // Parent constructor OO.ui.BarToolGroup.super.call( this, toolbar, config ); // Initialization this.$element.addClass( 'oo-ui-barToolGroup' ); }; /* Setup */ OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup ); /* Static Properties */ OO.ui.BarToolGroup.static.titleTooltips = true; OO.ui.BarToolGroup.static.accelTooltips = true; OO.ui.BarToolGroup.static.name = 'bar'; /** * Popup list of tools with an icon and optional label. * * @abstract * @class * @extends OO.ui.ToolGroup * @mixins OO.ui.IconElement * @mixins OO.ui.IndicatorElement * @mixins OO.ui.LabelElement * @mixins OO.ui.TitledElement * @mixins OO.ui.ClippableElement * * @constructor * @param {OO.ui.Toolbar} toolbar * @param {Object} [config] Configuration options * @cfg {string} [header] Text to display at the top of the pop-up */ OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolbar ) && config === undefined ) { config = toolbar; toolbar = config.toolbar; } // Configuration initialization config = config || {}; // Parent constructor OO.ui.PopupToolGroup.super.call( this, toolbar, config ); // Mixin constructors OO.ui.IconElement.call( this, config ); OO.ui.IndicatorElement.call( this, config ); OO.ui.LabelElement.call( this, config ); OO.ui.TitledElement.call( this, config ); OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) ); // Properties this.active = false; this.dragging = false; this.onBlurHandler = this.onBlur.bind( this ); this.$handle = $( '<span>' ); // Events this.$handle.on( { mousedown: this.onHandlePointerDown.bind( this ), mouseup: this.onHandlePointerUp.bind( this ) } ); // Initialization this.$handle .addClass( 'oo-ui-popupToolGroup-handle' ) .append( this.$icon, this.$label, this.$indicator ); // If the pop-up should have a header, add it to the top of the toolGroup. // Note: If this feature is useful for other widgets, we could abstract it into an // OO.ui.HeaderedElement mixin constructor. if ( config.header !== undefined ) { this.$group .prepend( $( '<span>' ) .addClass( 'oo-ui-popupToolGroup-header' ) .text( config.header ) ); } this.$element .addClass( 'oo-ui-popupToolGroup' ) .prepend( this.$handle ); }; /* Setup */ OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup ); OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IconElement ); OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IndicatorElement ); OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.LabelElement ); OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.TitledElement ); OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.ClippableElement ); /* Static Properties */ /* Methods */ /** * @inheritdoc */ OO.ui.PopupToolGroup.prototype.setDisabled = function () { // Parent method OO.ui.PopupToolGroup.super.prototype.setDisabled.apply( this, arguments ); if ( this.isDisabled() && this.isElementAttached() ) { this.setActive( false ); } }; /** * Handle focus being lost. * * The event is actually generated from a mouseup, so it is not a normal blur event object. * * @param {jQuery.Event} e Mouse up event */ OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) { // Only deactivate when clicking outside the dropdown element if ( $( e.target ).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element[ 0 ] ) { this.setActive( false ); } }; /** * @inheritdoc */ OO.ui.PopupToolGroup.prototype.onPointerUp = function ( e ) { // Only close toolgroup when a tool was actually selected if ( !this.isDisabled() && e.which === 1 && this.pressed && this.pressed === this.getTargetTool( e ) ) { this.setActive( false ); } return OO.ui.PopupToolGroup.super.prototype.onPointerUp.call( this, e ); }; /** * Handle mouse up events. * * @param {jQuery.Event} e Mouse up event */ OO.ui.PopupToolGroup.prototype.onHandlePointerUp = function () { return false; }; /** * Handle mouse down events. * * @param {jQuery.Event} e Mouse down event */ OO.ui.PopupToolGroup.prototype.onHandlePointerDown = function ( e ) { if ( !this.isDisabled() && e.which === 1 ) { this.setActive( !this.active ); } return false; }; /** * Switch into active mode. * * When active, mouseup events anywhere in the document will trigger deactivation. */ OO.ui.PopupToolGroup.prototype.setActive = function ( value ) { value = !!value; if ( this.active !== value ) { this.active = value; if ( value ) { this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler, true ); // Try anchoring the popup to the left first this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' ); this.toggleClipping( true ); if ( this.isClippedHorizontally() ) { // Anchoring to the left caused the popup to clip, so anchor it to the right instead this.toggleClipping( false ); this.$element .removeClass( 'oo-ui-popupToolGroup-left' ) .addClass( 'oo-ui-popupToolGroup-right' ); this.toggleClipping( true ); } } else { this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler, true ); this.$element.removeClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right' ); this.toggleClipping( false ); } } }; /** * Drop down list layout of tools as labeled icon buttons. * * This layout allows some tools to be collapsible, controlled by a "More" / "Fewer" option at the * bottom of the main list. These are not automatically positioned at the bottom of the list; you * may want to use the 'promote' and 'demote' configuration options to achieve this. * * @class * @extends OO.ui.PopupToolGroup * * @constructor * @param {OO.ui.Toolbar} toolbar * @param {Object} [config] Configuration options * @cfg {Array} [allowCollapse] List of tools that can be collapsed. Remaining tools will be always * shown. * @cfg {Array} [forceExpand] List of tools that *may not* be collapsed. All remaining tools will be * allowed to be collapsed. * @cfg {boolean} [expanded=false] Whether the collapsible tools are expanded by default */ OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolbar ) && config === undefined ) { config = toolbar; toolbar = config.toolbar; } // Configuration initialization config = config || {}; // Properties (must be set before parent constructor, which calls #populate) this.allowCollapse = config.allowCollapse; this.forceExpand = config.forceExpand; this.expanded = config.expanded !== undefined ? config.expanded : false; this.collapsibleTools = []; // Parent constructor OO.ui.ListToolGroup.super.call( this, toolbar, config ); // Initialization this.$element.addClass( 'oo-ui-listToolGroup' ); }; /* Setup */ OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup ); /* Static Properties */ OO.ui.ListToolGroup.static.accelTooltips = true; OO.ui.ListToolGroup.static.name = 'list'; /* Methods */ /** * @inheritdoc */ OO.ui.ListToolGroup.prototype.populate = function () { var i, len, allowCollapse = []; OO.ui.ListToolGroup.super.prototype.populate.call( this ); // Update the list of collapsible tools if ( this.allowCollapse !== undefined ) { allowCollapse = this.allowCollapse; } else if ( this.forceExpand !== undefined ) { allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand ); } this.collapsibleTools = []; for ( i = 0, len = allowCollapse.length; i < len; i++ ) { if ( this.tools[ allowCollapse[ i ] ] !== undefined ) { this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] ); } } // Keep at the end, even when tools are added this.$group.append( this.getExpandCollapseTool().$element ); this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 ); this.updateCollapsibleState(); }; OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () { if ( this.expandCollapseTool === undefined ) { var ExpandCollapseTool = function () { ExpandCollapseTool.super.apply( this, arguments ); }; OO.inheritClass( ExpandCollapseTool, OO.ui.Tool ); ExpandCollapseTool.prototype.onSelect = function () { this.toolGroup.expanded = !this.toolGroup.expanded; this.toolGroup.updateCollapsibleState(); this.setActive( false ); }; ExpandCollapseTool.prototype.onUpdateState = function () { // Do nothing. Tool interface requires an implementation of this function. }; ExpandCollapseTool.static.name = 'more-fewer'; this.expandCollapseTool = new ExpandCollapseTool( this ); } return this.expandCollapseTool; }; /** * @inheritdoc */ OO.ui.ListToolGroup.prototype.onPointerUp = function ( e ) { var ret = OO.ui.ListToolGroup.super.prototype.onPointerUp.call( this, e ); // Do not close the popup when the user wants to show more/fewer tools if ( $( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length ) { // Prevent the popup list from being hidden this.setActive( true ); } return ret; }; OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () { var i, len; this.getExpandCollapseTool() .setIcon( this.expanded ? 'collapse' : 'expand' ) .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) ); for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) { this.collapsibleTools[ i ].toggle( this.expanded ); } }; /** * Drop down menu layout of tools as selectable menu items. * * @class * @extends OO.ui.PopupToolGroup * * @constructor * @param {OO.ui.Toolbar} toolbar * @param {Object} [config] Configuration options */ OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolbar ) && config === undefined ) { config = toolbar; toolbar = config.toolbar; } // Configuration initialization config = config || {}; // Parent constructor OO.ui.MenuToolGroup.super.call( this, toolbar, config ); // Events this.toolbar.connect( this, { updateState: 'onUpdateState' } ); // Initialization this.$element.addClass( 'oo-ui-menuToolGroup' ); }; /* Setup */ OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup ); /* Static Properties */ OO.ui.MenuToolGroup.static.accelTooltips = true; OO.ui.MenuToolGroup.static.name = 'menu'; /* Methods */ /** * Handle the toolbar state being updated. * * When the state changes, the title of each active item in the menu will be joined together and * used as a label for the group. The label will be empty if none of the items are active. */ OO.ui.MenuToolGroup.prototype.onUpdateState = function () { var name, labelTexts = []; for ( name in this.tools ) { if ( this.tools[ name ].isActive() ) { labelTexts.push( this.tools[ name ].getTitle() ); } } this.setLabel( labelTexts.join( ', ' ) || ' ' ); }; /** * Tool that shows a popup when selected. * * @abstract * @class * @extends OO.ui.Tool * @mixins OO.ui.PopupElement * * @constructor * @param {OO.ui.ToolGroup} toolGroup * @param {Object} [config] Configuration options */ OO.ui.PopupTool = function OoUiPopupTool( toolGroup, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolGroup ) && config === undefined ) { config = toolGroup; toolGroup = config.toolGroup; } // Parent constructor OO.ui.PopupTool.super.call( this, toolGroup, config ); // Mixin constructors OO.ui.PopupElement.call( this, config ); // Initialization this.$element .addClass( 'oo-ui-popupTool' ) .append( this.popup.$element ); }; /* Setup */ OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool ); OO.mixinClass( OO.ui.PopupTool, OO.ui.PopupElement ); /* Methods */ /** * Handle the tool being selected. * * @inheritdoc */ OO.ui.PopupTool.prototype.onSelect = function () { if ( !this.isDisabled() ) { this.popup.toggle(); } this.setActive( false ); return false; }; /** * Handle the toolbar state being updated. * * @inheritdoc */ OO.ui.PopupTool.prototype.onUpdateState = function () { this.setActive( false ); }; /** * Tool that has a tool group inside. This is a bad workaround for the lack of proper hierarchical * menus in toolbars (T74159). * * @abstract * @class * @extends OO.ui.Tool * * @constructor * @param {OO.ui.ToolGroup} toolGroup * @param {Object} [config] Configuration options */ OO.ui.ToolGroupTool = function OoUiToolGroupTool( toolGroup, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolGroup ) && config === undefined ) { config = toolGroup; toolGroup = config.toolGroup; } // Parent constructor OO.ui.ToolGroupTool.super.call( this, toolGroup, config ); // Properties this.innerToolGroup = this.createGroup( this.constructor.static.groupConfig ); // Initialization this.$link.remove(); this.$element .addClass( 'oo-ui-toolGroupTool' ) .append( this.innerToolGroup.$element ); }; /* Setup */ OO.inheritClass( OO.ui.ToolGroupTool, OO.ui.Tool ); /* Static Properties */ /** * Tool group configuration. See OO.ui.Toolbar#setup for the accepted values. * * @property {Object.<string,Array>} */ OO.ui.ToolGroupTool.static.groupConfig = {}; /* Methods */ /** * Handle the tool being selected. * * @inheritdoc */ OO.ui.ToolGroupTool.prototype.onSelect = function () { this.innerToolGroup.setActive( !this.innerToolGroup.active ); return false; }; /** * Handle the toolbar state being updated. * * @inheritdoc */ OO.ui.ToolGroupTool.prototype.onUpdateState = function () { this.setActive( false ); }; /** * Build a OO.ui.ToolGroup from the configuration. * * @param {Object.<string,Array>} group Tool group configuration. See OO.ui.Toolbar#setup for the * accepted values. * @return {OO.ui.ListToolGroup} */ OO.ui.ToolGroupTool.prototype.createGroup = function ( group ) { if ( group.include === '*' ) { // Apply defaults to catch-all groups if ( group.label === undefined ) { group.label = OO.ui.msg( 'ooui-toolbar-more' ); } } return this.toolbar.getToolGroupFactory().create( 'list', this.toolbar, group ); }; /** * Mixin for OO.ui.Widget subclasses to provide OO.ui.GroupElement. * * Use together with OO.ui.ItemWidget to make disabled state inheritable. * * @private * @abstract * @class * @extends OO.ui.GroupElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.GroupWidget = function OoUiGroupWidget( config ) { // Parent constructor OO.ui.GroupWidget.super.call( this, config ); }; /* Setup */ OO.inheritClass( OO.ui.GroupWidget, OO.ui.GroupElement ); /* Methods */ /** * Set the disabled state of the widget. * * This will also update the disabled state of child widgets. * * @param {boolean} disabled Disable widget * @chainable */ OO.ui.GroupWidget.prototype.setDisabled = function ( disabled ) { var i, len; // Parent method // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget OO.ui.Widget.prototype.setDisabled.call( this, disabled ); // During construction, #setDisabled is called before the OO.ui.GroupElement constructor if ( this.items ) { for ( i = 0, len = this.items.length; i < len; i++ ) { this.items[ i ].updateDisabled(); } } return this; }; /** * Mixin for widgets used as items in widgets that inherit OO.ui.GroupWidget. * * Item widgets have a reference to a OO.ui.GroupWidget while they are attached to the group. This * allows bidirectional communication. * * Use together with OO.ui.GroupWidget to make disabled state inheritable. * * @private * @abstract * @class * * @constructor */ OO.ui.ItemWidget = function OoUiItemWidget() { // }; /* Methods */ /** * Check if widget is disabled. * * Checks parent if present, making disabled state inheritable. * * @return {boolean} Widget is disabled */ OO.ui.ItemWidget.prototype.isDisabled = function () { return this.disabled || ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() ); }; /** * Set group element is in. * * @param {OO.ui.GroupElement|null} group Group element, null if none * @chainable */ OO.ui.ItemWidget.prototype.setElementGroup = function ( group ) { // Parent method // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element OO.ui.Element.prototype.setElementGroup.call( this, group ); // Initialize item disabled states this.updateDisabled(); return this; }; /** * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}. * Controls include moving items up and down, removing items, and adding different kinds of items. * ####Currently, this class is only used by {@link OO.ui.BookletLayout BookletLayouts}.#### * * @class * @extends OO.ui.Widget * @mixins OO.ui.GroupElement * @mixins OO.ui.IconElement * * @constructor * @param {OO.ui.OutlineSelectWidget} outline Outline to control * @param {Object} [config] Configuration options * @cfg {Object} [abilities] List of abilties * @cfg {boolean} [abilities.move=true] Allow moving movable items * @cfg {boolean} [abilities.remove=true] Allow removing removable items */ OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( outline ) && config === undefined ) { config = outline; outline = config.outline; } // Configuration initialization config = $.extend( { icon: 'add' }, config ); // Parent constructor OO.ui.OutlineControlsWidget.super.call( this, config ); // Mixin constructors OO.ui.GroupElement.call( this, config ); OO.ui.IconElement.call( this, config ); // Properties this.outline = outline; this.$movers = $( '<div>' ); this.upButton = new OO.ui.ButtonWidget( { framed: false, icon: 'collapse', title: OO.ui.msg( 'ooui-outline-control-move-up' ) } ); this.downButton = new OO.ui.ButtonWidget( { framed: false, icon: 'expand', title: OO.ui.msg( 'ooui-outline-control-move-down' ) } ); this.removeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'remove', title: OO.ui.msg( 'ooui-outline-control-remove' ) } ); this.abilities = { move: true, remove: true }; // Events outline.connect( this, { select: 'onOutlineChange', add: 'onOutlineChange', remove: 'onOutlineChange' } ); this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } ); this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } ); this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } ); // Initialization this.$element.addClass( 'oo-ui-outlineControlsWidget' ); this.$group.addClass( 'oo-ui-outlineControlsWidget-items' ); this.$movers .addClass( 'oo-ui-outlineControlsWidget-movers' ) .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element ); this.$element.append( this.$icon, this.$group, this.$movers ); this.setAbilities( config.abilities || {} ); }; /* Setup */ OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.GroupElement ); OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.IconElement ); /* Events */ /** * @event move * @param {number} places Number of places to move */ /** * @event remove */ /* Methods */ /** * Set abilities. * * @param {Object} abilities List of abilties * @param {boolean} [abilities.move] Allow moving movable items * @param {boolean} [abilities.remove] Allow removing removable items */ OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) { var ability; for ( ability in this.abilities ) { if ( abilities[ability] !== undefined ) { this.abilities[ability] = !!abilities[ability]; } } this.onOutlineChange(); }; /** * * @private * Handle outline change events. */ OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () { var i, len, firstMovable, lastMovable, items = this.outline.getItems(), selectedItem = this.outline.getSelectedItem(), movable = this.abilities.move && selectedItem && selectedItem.isMovable(), removable = this.abilities.remove && selectedItem && selectedItem.isRemovable(); if ( movable ) { i = -1; len = items.length; while ( ++i < len ) { if ( items[ i ].isMovable() ) { firstMovable = items[ i ]; break; } } i = len; while ( i-- ) { if ( items[ i ].isMovable() ) { lastMovable = items[ i ]; break; } } } this.upButton.setDisabled( !movable || selectedItem === firstMovable ); this.downButton.setDisabled( !movable || selectedItem === lastMovable ); this.removeButton.setDisabled( !removable ); }; /** * ToggleWidget is mixed into other classes to create widgets with an on/off state. * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples. * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {boolean} [value=false] The toggle’s initial on/off state. * By default, the toggle is in the 'off' state. */ OO.ui.ToggleWidget = function OoUiToggleWidget( config ) { // Configuration initialization config = config || {}; // Properties this.value = null; // Initialization this.$element.addClass( 'oo-ui-toggleWidget' ); this.setValue( !!config.value ); }; /* Events */ /** * @event change * * A change event is emitted when the on/off state of the toggle changes. * * @param {boolean} value Value representing the new state of the toggle */ /* Methods */ /** * Get the value representing the toggle’s state. * * @return {boolean} The on/off state of the toggle */ OO.ui.ToggleWidget.prototype.getValue = function () { return this.value; }; /** * Set the state of the toggle: `true` for 'on', `false' for 'off'. * * @param {boolean} value The state of the toggle * @fires change * @chainable */ OO.ui.ToggleWidget.prototype.setValue = function ( value ) { value = !!value; if ( this.value !== value ) { this.value = value; this.emit( 'change', value ); this.$element.toggleClass( 'oo-ui-toggleWidget-on', value ); this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value ); this.$element.attr( 'aria-checked', value.toString() ); } return this; }; /** * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added, * removed, and cleared from the group. * * @example * // Example: A ButtonGroupWidget with two buttons * var button1 = new OO.ui.PopupButtonWidget( { * label: 'Select a category', * icon: 'menu', * popup: { * $content: $( '<p>List of categories...</p>' ), * padded: true, * align: 'left' * } * } ); * var button2 = new OO.ui.ButtonWidget( { * label: 'Add item' * }); * var buttonGroup = new OO.ui.ButtonGroupWidget( { * items: [button1, button2] * } ); * $( 'body' ).append( buttonGroup.$element ); * * @class * @extends OO.ui.Widget * @mixins OO.ui.GroupElement * * @constructor * @param {Object} [config] Configuration options * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add */ OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.ButtonGroupWidget.super.call( this, config ); // Mixin constructors OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) ); // Initialization this.$element.addClass( 'oo-ui-buttonGroupWidget' ); if ( Array.isArray( config.items ) ) { this.addItems( config.items ); } }; /* Setup */ OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.GroupElement ); /** * ButtonWidget is a generic widget for buttons. A wide variety of looks, * feels, and functionality can be customized via the class’s configuration options * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information * and examples. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches * * @example * // A button widget * var button = new OO.ui.ButtonWidget( { * label: 'Button with Icon', * icon: 'remove', * iconTitle: 'Remove' * } ); * $( 'body' ).append( button.$element ); * * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class. * * @class * @extends OO.ui.Widget * @mixins OO.ui.ButtonElement * @mixins OO.ui.IconElement * @mixins OO.ui.IndicatorElement * @mixins OO.ui.LabelElement * @mixins OO.ui.TitledElement * @mixins OO.ui.FlaggedElement * @mixins OO.ui.TabIndexedElement * * @constructor * @param {Object} [config] Configuration options * @cfg {string} [href] Hyperlink to visit when the button is clicked. * @cfg {string} [target] The frame or window in which to open the hyperlink. * @cfg {boolean} [noFollow] Search engine traversal hint (default: true) */ OO.ui.ButtonWidget = function OoUiButtonWidget( config ) { // Configuration initialization // FIXME: The `nofollow` alias is deprecated and will be removed (T89767) config = $.extend( { noFollow: config && config.nofollow }, config ); // Parent constructor OO.ui.ButtonWidget.super.call( this, config ); // Mixin constructors OO.ui.ButtonElement.call( this, config ); OO.ui.IconElement.call( this, config ); OO.ui.IndicatorElement.call( this, config ); OO.ui.LabelElement.call( this, config ); OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) ); OO.ui.FlaggedElement.call( this, config ); OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) ); // Properties this.href = null; this.target = null; this.noFollow = false; this.isHyperlink = false; // Initialization this.$button.append( this.$icon, this.$label, this.$indicator ); this.$element .addClass( 'oo-ui-buttonWidget' ) .append( this.$button ); this.setHref( config.href ); this.setTarget( config.target ); this.setNoFollow( config.noFollow ); }; /* Setup */ OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.ButtonWidget, OO.ui.ButtonElement ); OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IconElement ); OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IndicatorElement ); OO.mixinClass( OO.ui.ButtonWidget, OO.ui.LabelElement ); OO.mixinClass( OO.ui.ButtonWidget, OO.ui.TitledElement ); OO.mixinClass( OO.ui.ButtonWidget, OO.ui.FlaggedElement ); OO.mixinClass( OO.ui.ButtonWidget, OO.ui.TabIndexedElement ); /* Methods */ /** * @inheritdoc */ OO.ui.ButtonWidget.prototype.onMouseDown = function ( e ) { if ( !this.isDisabled() ) { // Remove the tab-index while the button is down to prevent the button from stealing focus this.$button.removeAttr( 'tabindex' ); } return OO.ui.ButtonElement.prototype.onMouseDown.call( this, e ); }; /** * @inheritdoc */ OO.ui.ButtonWidget.prototype.onMouseUp = function ( e ) { if ( !this.isDisabled() ) { // Restore the tab-index after the button is up to restore the button's accessibility this.$button.attr( 'tabindex', this.tabIndex ); } return OO.ui.ButtonElement.prototype.onMouseUp.call( this, e ); }; /** * @inheritdoc */ OO.ui.ButtonWidget.prototype.onClick = function ( e ) { var ret = OO.ui.ButtonElement.prototype.onClick.call( this, e ); if ( this.isHyperlink ) { return true; } return ret; }; /** * @inheritdoc */ OO.ui.ButtonWidget.prototype.onKeyPress = function ( e ) { var ret = OO.ui.ButtonElement.prototype.onKeyPress.call( this, e ); if ( this.isHyperlink ) { return true; } return ret; }; /** * Get hyperlink location. * * @return {string} Hyperlink location */ OO.ui.ButtonWidget.prototype.getHref = function () { return this.href; }; /** * Get hyperlink target. * * @return {string} Hyperlink target */ OO.ui.ButtonWidget.prototype.getTarget = function () { return this.target; }; /** * Get search engine traversal hint. * * @return {boolean} Whether search engines should avoid traversing this hyperlink */ OO.ui.ButtonWidget.prototype.getNoFollow = function () { return this.noFollow; }; /** * Set hyperlink location. * * @param {string|null} href Hyperlink location, null to remove */ OO.ui.ButtonWidget.prototype.setHref = function ( href ) { href = typeof href === 'string' ? href : null; if ( href !== this.href ) { this.href = href; if ( href !== null ) { this.$button.attr( 'href', href ); this.isHyperlink = true; } else { this.$button.removeAttr( 'href' ); this.isHyperlink = false; } } return this; }; /** * Set hyperlink target. * * @param {string|null} target Hyperlink target, null to remove */ OO.ui.ButtonWidget.prototype.setTarget = function ( target ) { target = typeof target === 'string' ? target : null; if ( target !== this.target ) { this.target = target; if ( target !== null ) { this.$button.attr( 'target', target ); } else { this.$button.removeAttr( 'target' ); } } return this; }; /** * Set search engine traversal hint. * * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink */ OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) { noFollow = typeof noFollow === 'boolean' ? noFollow : true; if ( noFollow !== this.noFollow ) { this.noFollow = noFollow; if ( noFollow ) { this.$button.attr( 'rel', 'nofollow' ); } else { this.$button.removeAttr( 'rel' ); } } return this; }; /** * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action. * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability * of the actions. * * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}. * Please see the [OOjs UI documentation on MediaWiki] [1] for more information * and examples. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets * * @class * @extends OO.ui.ButtonWidget * @mixins OO.ui.PendingElement * * @constructor * @param {Object} [config] Configuration options * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’). * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method * for more information about setting modes. * @cfg {boolean} [framed=false] Render the action button with a frame */ OO.ui.ActionWidget = function OoUiActionWidget( config ) { // Configuration initialization config = $.extend( { framed: false }, config ); // Parent constructor OO.ui.ActionWidget.super.call( this, config ); // Mixin constructors OO.ui.PendingElement.call( this, config ); // Properties this.action = config.action || ''; this.modes = config.modes || []; this.width = 0; this.height = 0; // Initialization this.$element.addClass( 'oo-ui-actionWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget ); OO.mixinClass( OO.ui.ActionWidget, OO.ui.PendingElement ); /* Events */ /** * A resize event is emitted when the size of the widget changes. * * @event resize */ /* Methods */ /** * Check if the action is configured to be available in the specified `mode`. * * @param {string} mode Name of mode * @return {boolean} The action is configured with the mode */ OO.ui.ActionWidget.prototype.hasMode = function ( mode ) { return this.modes.indexOf( mode ) !== -1; }; /** * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’). * * @return {string} */ OO.ui.ActionWidget.prototype.getAction = function () { return this.action; }; /** * Get the symbolic name of the mode or modes for which the action is configured to be available. * * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method. * Only actions that are configured to be avaiable in the current mode will be visible. All other actions * are hidden. * * @return {string[]} */ OO.ui.ActionWidget.prototype.getModes = function () { return this.modes.slice(); }; /** * Emit a resize event if the size has changed. * * @private * @chainable */ OO.ui.ActionWidget.prototype.propagateResize = function () { var width, height; if ( this.isElementAttached() ) { width = this.$element.width(); height = this.$element.height(); if ( width !== this.width || height !== this.height ) { this.width = width; this.height = height; this.emit( 'resize' ); } } return this; }; /** * @inheritdoc */ OO.ui.ActionWidget.prototype.setIcon = function () { // Mixin method OO.ui.IconElement.prototype.setIcon.apply( this, arguments ); this.propagateResize(); return this; }; /** * @inheritdoc */ OO.ui.ActionWidget.prototype.setLabel = function () { // Mixin method OO.ui.LabelElement.prototype.setLabel.apply( this, arguments ); this.propagateResize(); return this; }; /** * @inheritdoc */ OO.ui.ActionWidget.prototype.setFlags = function () { // Mixin method OO.ui.FlaggedElement.prototype.setFlags.apply( this, arguments ); this.propagateResize(); return this; }; /** * @inheritdoc */ OO.ui.ActionWidget.prototype.clearFlags = function () { // Mixin method OO.ui.FlaggedElement.prototype.clearFlags.apply( this, arguments ); this.propagateResize(); return this; }; /** * Toggle the visibility of the action button. * * @param {boolean} [show] Show button, omit to toggle visibility * @chainable */ OO.ui.ActionWidget.prototype.toggle = function () { // Parent method OO.ui.ActionWidget.super.prototype.toggle.apply( this, arguments ); this.propagateResize(); return this; }; /** * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget}, * which is used to display additional information or options. * * @example * // Example of a popup button. * var popupButton = new OO.ui.PopupButtonWidget( { * label: 'Popup button with options', * icon: 'menu', * popup: { * $content: $( '<p>Additional options here.</p>' ), * padded: true, * align: 'left' * } * } ); * // Append the button to the DOM. * $( 'body' ).append( popupButton.$element ); * * @class * @extends OO.ui.ButtonWidget * @mixins OO.ui.PopupElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) { // Parent constructor OO.ui.PopupButtonWidget.super.call( this, config ); // Mixin constructors OO.ui.PopupElement.call( this, config ); // Events this.connect( this, { click: 'onAction' } ); // Initialization this.$element .addClass( 'oo-ui-popupButtonWidget' ) .attr( 'aria-haspopup', 'true' ) .append( this.popup.$element ); }; /* Setup */ OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget ); OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.PopupElement ); /* Methods */ /** * Handle the button action being triggered. * * @private */ OO.ui.PopupButtonWidget.prototype.onAction = function () { this.popup.toggle(); }; /** * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be * configured with {@link OO.ui.IconElement icons}, {@link OO.ui.IndicatorElement indicators}, * {@link OO.ui.TitledElement titles}, {@link OO.ui.FlaggedElement styling flags}, * and {@link OO.ui.LabelElement labels}. Please see * the [OOjs UI documentation][1] on MediaWiki for more information. * * @example * // Toggle buttons in the 'off' and 'on' state. * var toggleButton1 = new OO.ui.ToggleButtonWidget( { * label: 'Toggle Button off' * } ); * var toggleButton2 = new OO.ui.ToggleButtonWidget( { * label: 'Toggle Button on', * value: true * } ); * // Append the buttons to the DOM. * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons * * @class * @extends OO.ui.ButtonWidget * @mixins OO.ui.ToggleWidget * * @constructor * @param {Object} [config] Configuration options * @cfg {boolean} [value=false] The toggle button’s initial on/off * state. By default, the button is in the 'off' state. */ OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.ToggleButtonWidget.super.call( this, config ); // Mixin constructors OO.ui.ToggleWidget.call( this, config ); // Events this.connect( this, { click: 'onAction' } ); // Initialization this.$element.addClass( 'oo-ui-toggleButtonWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ButtonWidget ); OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget ); /* Methods */ /** * * @private * Handle the button action being triggered. */ OO.ui.ToggleButtonWidget.prototype.onAction = function () { this.setValue( !this.value ); }; /** * @inheritdoc */ OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) { value = !!value; if ( value !== this.value ) { this.$button.attr( 'aria-pressed', value.toString() ); this.setActive( value ); } // Parent method (from mixin) OO.ui.ToggleWidget.prototype.setValue.call( this, value ); return this; }; /** * DropdownWidgets are not menus themselves, rather they contain a menu of options created with * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that * users can interact with it. * * @example * // Example: A DropdownWidget with a menu that contains three options * var dropDown = new OO.ui.DropdownWidget( { * label: 'Dropdown menu: Select a menu option', * menu: { * items: [ * new OO.ui.MenuOptionWidget( { * data: 'a', * label: 'First' * } ), * new OO.ui.MenuOptionWidget( { * data: 'b', * label: 'Second' * } ), * new OO.ui.MenuOptionWidget( { * data: 'c', * label: 'Third' * } ) * ] * } * } ); * * $( 'body' ).append( dropDown.$element ); * * For more information, please see the [OOjs UI documentation on MediaWiki] [1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options * * @class * @extends OO.ui.Widget * @mixins OO.ui.IconElement * @mixins OO.ui.IndicatorElement * @mixins OO.ui.LabelElement * @mixins OO.ui.TitledElement * @mixins OO.ui.TabIndexedElement * * @constructor * @param {Object} [config] Configuration options * @cfg {Object} [menu] Configuration options to pass to menu widget */ OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) { // Configuration initialization config = $.extend( { indicator: 'down' }, config ); // Parent constructor OO.ui.DropdownWidget.super.call( this, config ); // Properties (must be set before TabIndexedElement constructor call) this.$handle = this.$( '<span>' ); // Mixin constructors OO.ui.IconElement.call( this, config ); OO.ui.IndicatorElement.call( this, config ); OO.ui.LabelElement.call( this, config ); OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) ); OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) ); // Properties this.menu = new OO.ui.MenuSelectWidget( $.extend( { widget: this }, config.menu ) ); // Events this.$handle.on( { click: this.onClick.bind( this ), keypress: this.onKeyPress.bind( this ) } ); this.menu.connect( this, { select: 'onMenuSelect' } ); // Initialization this.$handle .addClass( 'oo-ui-dropdownWidget-handle' ) .append( this.$icon, this.$label, this.$indicator ); this.$element .addClass( 'oo-ui-dropdownWidget' ) .append( this.$handle, this.menu.$element ); }; /* Setup */ OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.DropdownWidget, OO.ui.IconElement ); OO.mixinClass( OO.ui.DropdownWidget, OO.ui.IndicatorElement ); OO.mixinClass( OO.ui.DropdownWidget, OO.ui.LabelElement ); OO.mixinClass( OO.ui.DropdownWidget, OO.ui.TitledElement ); OO.mixinClass( OO.ui.DropdownWidget, OO.ui.TabIndexedElement ); /* Methods */ /** * Get the menu. * * @return {OO.ui.MenuSelectWidget} Menu of widget */ OO.ui.DropdownWidget.prototype.getMenu = function () { return this.menu; }; /** * Handles menu select events. * * @private * @param {OO.ui.MenuOptionWidget} item Selected menu item */ OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) { var selectedLabel; if ( !item ) { return; } selectedLabel = item.getLabel(); // If the label is a DOM element, clone it, because setLabel will append() it if ( selectedLabel instanceof jQuery ) { selectedLabel = selectedLabel.clone(); } this.setLabel( selectedLabel ); }; /** * Handle mouse click events. * * @private * @param {jQuery.Event} e Mouse click event */ OO.ui.DropdownWidget.prototype.onClick = function ( e ) { if ( !this.isDisabled() && e.which === 1 ) { this.menu.toggle(); } return false; }; /** * Handle key press events. * * @private * @param {jQuery.Event} e Key press event */ OO.ui.DropdownWidget.prototype.onKeyPress = function ( e ) { if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) { this.menu.toggle(); return false; } }; /** * IconWidget is a generic widget for {@link OO.ui.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget, * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1] * for a list of icons included in the library. * * @example * // An icon widget with a label * var myIcon = new OO.ui.IconWidget( { * icon: 'help', * iconTitle: 'Help' * } ); * // Create a label. * var iconLabel = new OO.ui.LabelWidget( { * label: 'Help' * } ); * $( 'body' ).append( myIcon.$element, iconLabel.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons * * @class * @extends OO.ui.Widget * @mixins OO.ui.IconElement * @mixins OO.ui.TitledElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.IconWidget = function OoUiIconWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.IconWidget.super.call( this, config ); // Mixin constructors OO.ui.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) ); OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) ); // Initialization this.$element.addClass( 'oo-ui-iconWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.IconWidget, OO.ui.IconElement ); OO.mixinClass( OO.ui.IconWidget, OO.ui.TitledElement ); /* Static Properties */ OO.ui.IconWidget.static.tagName = 'span'; /** * IndicatorWidgets create indicators, which are small graphics that are generally used to draw * attention to the status of an item or to clarify the function of a control. For a list of * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1]. * * @example * // Example of an indicator widget * var indicator1 = new OO.ui.IndicatorWidget( { * indicator: 'alert' * } ); * * // Create a fieldset layout to add a label * var fieldset = new OO.ui.FieldsetLayout(); * fieldset.addItems( [ * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } ) * ] ); * $( 'body' ).append( fieldset.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators * * @class * @extends OO.ui.Widget * @mixins OO.ui.IndicatorElement * @mixins OO.ui.TitledElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.IndicatorWidget.super.call( this, config ); // Mixin constructors OO.ui.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) ); OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) ); // Initialization this.$element.addClass( 'oo-ui-indicatorWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.IndicatorElement ); OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.TitledElement ); /* Static Properties */ OO.ui.IndicatorWidget.static.tagName = 'span'; /** * InputWidget is the base class for all input widgets, which * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs}, * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}. * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs * * @abstract * @class * @extends OO.ui.Widget * @mixins OO.ui.FlaggedElement * @mixins OO.ui.TabIndexedElement * * @constructor * @param {Object} [config] Configuration options * @cfg {string} [name=''] The value of the input’s HTML `name` attribute. * @cfg {string} [value=''] The value of the input. * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input * before it is accepted. */ OO.ui.InputWidget = function OoUiInputWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.InputWidget.super.call( this, config ); // Properties this.$input = this.getInputElement( config ); this.value = ''; this.inputFilter = config.inputFilter; // Mixin constructors OO.ui.FlaggedElement.call( this, config ); OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) ); // Events this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) ); // Initialization this.$input .attr( 'name', config.name ) .prop( 'disabled', this.isDisabled() ); this.$element.addClass( 'oo-ui-inputWidget' ).append( this.$input, $( '<span>' ) ); this.setValue( config.value ); }; /* Setup */ OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.InputWidget, OO.ui.FlaggedElement ); OO.mixinClass( OO.ui.InputWidget, OO.ui.TabIndexedElement ); /* Events */ /** * @event change * * A change event is emitted when the value of the input changes. * * @param {string} value */ /* Methods */ /** * Get input element. * * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in * different circumstances. The element must have a `value` property (like form elements). * * @private * @param {Object} config Configuration options * @return {jQuery} Input element */ OO.ui.InputWidget.prototype.getInputElement = function () { return $( '<input>' ); }; /** * Handle potentially value-changing events. * * @private * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event */ OO.ui.InputWidget.prototype.onEdit = function () { var widget = this; if ( !this.isDisabled() ) { // Allow the stack to clear so the value will be updated setTimeout( function () { widget.setValue( widget.$input.val() ); } ); } }; /** * Get the value of the input. * * @return {string} Input value */ OO.ui.InputWidget.prototype.getValue = function () { // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify // it, and we won't know unless they're kind enough to trigger a 'change' event. var value = this.$input.val(); if ( this.value !== value ) { this.setValue( value ); } return this.value; }; /** * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right). * * @param {boolean} isRTL * Direction is right-to-left */ OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) { this.$input.prop( 'dir', isRTL ? 'rtl' : 'ltr' ); }; /** * Set the value of the input. * * @param {string} value New value * @fires change * @chainable */ OO.ui.InputWidget.prototype.setValue = function ( value ) { value = this.cleanUpValue( value ); // Update the DOM if it has changed. Note that with cleanUpValue, it // is possible for the DOM value to change without this.value changing. if ( this.$input.val() !== value ) { this.$input.val( value ); } if ( this.value !== value ) { this.value = value; this.emit( 'change', this.value ); } return this; }; /** * Clean up incoming value. * * Ensures value is a string, and converts undefined and null to empty string. * * @private * @param {string} value Original value * @return {string} Cleaned up value */ OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) { if ( value === undefined || value === null ) { return ''; } else if ( this.inputFilter ) { return this.inputFilter( String( value ) ); } else { return String( value ); } }; /** * Simulate the behavior of clicking on a label bound to this input. This method is only called by * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be * called directly. */ OO.ui.InputWidget.prototype.simulateLabelClick = function () { if ( !this.isDisabled() ) { if ( this.$input.is( ':checkbox, :radio' ) ) { this.$input.click(); } if ( this.$input.is( ':input' ) ) { this.$input[ 0 ].focus(); } } }; /** * @inheritdoc */ OO.ui.InputWidget.prototype.setDisabled = function ( state ) { OO.ui.InputWidget.super.prototype.setDisabled.call( this, state ); if ( this.$input ) { this.$input.prop( 'disabled', this.isDisabled() ); } return this; }; /** * Focus the input. * * @chainable */ OO.ui.InputWidget.prototype.focus = function () { this.$input[ 0 ].focus(); return this; }; /** * Blur the input. * * @chainable */ OO.ui.InputWidget.prototype.blur = function () { this.$input[ 0 ].blur(); return this; }; /** * ButtonInputWidget is used to submit HTML forms and is intended to be used within * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the * [OOjs UI documentation on MediaWiki] [1] for more information. * * @example * // A ButtonInputWidget rendered as an HTML button, the default. * var button = new OO.ui.ButtonInputWidget( { * label: 'Input button', * icon: 'check', * value: 'check' * } ); * $( 'body' ).append( button.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs * * @class * @extends OO.ui.InputWidget * @mixins OO.ui.ButtonElement * @mixins OO.ui.IconElement * @mixins OO.ui.IndicatorElement * @mixins OO.ui.LabelElement * @mixins OO.ui.TitledElement * @mixins OO.ui.FlaggedElement * * @constructor * @param {Object} [config] Configuration options * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'. * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default. * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators}, * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only * be set to `true` when there’s need to support IE6 in a form with multiple buttons. */ OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) { // Configuration initialization config = $.extend( { type: 'button', useInputTag: false }, config ); // Properties (must be set before parent constructor, which calls #setValue) this.useInputTag = config.useInputTag; // Parent constructor OO.ui.ButtonInputWidget.super.call( this, config ); // Mixin constructors OO.ui.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) ); OO.ui.IconElement.call( this, config ); OO.ui.IndicatorElement.call( this, config ); OO.ui.LabelElement.call( this, config ); OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) ); OO.ui.FlaggedElement.call( this, config ); // Initialization if ( !config.useInputTag ) { this.$input.append( this.$icon, this.$label, this.$indicator ); } this.$element.addClass( 'oo-ui-buttonInputWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget ); OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.ButtonElement ); OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.IconElement ); OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.IndicatorElement ); OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.LabelElement ); OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.TitledElement ); OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.FlaggedElement ); /* Methods */ /** * @inheritdoc * @private */ OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) { var html = '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + config.type + '">'; return $( html ); }; /** * Set label value. * * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag. * * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or * text, or `null` for no label * @chainable */ OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) { OO.ui.LabelElement.prototype.setLabel.call( this, label ); if ( this.useInputTag ) { if ( typeof label === 'function' ) { label = OO.ui.resolveMsg( label ); } if ( label instanceof jQuery ) { label = label.text(); } if ( !label ) { label = ''; } this.$input.val( label ); } return this; }; /** * Set the value of the input. * * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as * they do not support {@link #value values}. * * @param {string} value New value * @chainable */ OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) { if ( !this.useInputTag ) { OO.ui.ButtonInputWidget.super.prototype.setValue.call( this, value ); } return this; }; /** * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value. * Note that these {@link OO.ui.InputWidget input widgets} are best laid out * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline} * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1]. * * @example * // An example of selected, unselected, and disabled checkbox inputs * var checkbox1=new OO.ui.CheckboxInputWidget( { * value: 'a', * selected: true * } ); * var checkbox2=new OO.ui.CheckboxInputWidget( { * value: 'b' * } ); * var checkbox3=new OO.ui.CheckboxInputWidget( { * value:'c', * disabled: true * } ); * // Create a fieldset layout with fields for each checkbox. * var fieldset = new OO.ui.FieldsetLayout( { * label: 'Checkboxes' * } ); * fieldset.addItems( [ * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ), * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ), * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ), * ] ); * $( 'body' ).append( fieldset.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs * * @class * @extends OO.ui.InputWidget * * @constructor * @param {Object} [config] Configuration options * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected. */ OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.CheckboxInputWidget.super.call( this, config ); // Initialization this.$element.addClass( 'oo-ui-checkboxInputWidget' ); this.setSelected( config.selected !== undefined ? config.selected : false ); }; /* Setup */ OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget ); /* Methods */ /** * @inheritdoc * @private */ OO.ui.CheckboxInputWidget.prototype.getInputElement = function () { return $( '<input type="checkbox" />' ); }; /** * @inheritdoc */ OO.ui.CheckboxInputWidget.prototype.onEdit = function () { var widget = this; if ( !this.isDisabled() ) { // Allow the stack to clear so the value will be updated setTimeout( function () { widget.setSelected( widget.$input.prop( 'checked' ) ); } ); } }; /** * Set selection state of this checkbox. * * @param {boolean} state `true` for selected * @chainable */ OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) { state = !!state; if ( this.selected !== state ) { this.selected = state; this.$input.prop( 'checked', this.selected ); this.emit( 'change', this.selected ); } return this; }; /** * Check if this checkbox is selected. * * @return {boolean} Checkbox is selected */ OO.ui.CheckboxInputWidget.prototype.isSelected = function () { // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify // it, and we won't know unless they're kind enough to trigger a 'change' event. var selected = this.$input.prop( 'checked' ); if ( this.selected !== selected ) { this.setSelected( selected ); } return this.selected; }; /** * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used * within a {@link OO.ui.FormLayout form}. The selected value is synchronized with the value * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for * more information about input widgets. * * @example * // Example: A DropdownInputWidget with three options * var dropDown = new OO.ui.DropdownInputWidget( { * label: 'Dropdown menu: Select a menu option', * options: [ * { data: 'a', label: 'First' } , * { data: 'b', label: 'Second'} , * { data: 'c', label: 'Third' } * ] * } ); * $( 'body' ).append( dropDown.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs * * @class * @extends OO.ui.InputWidget * * @constructor * @param {Object} [config] Configuration options * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }` */ OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) { // Configuration initialization config = config || {}; // Properties (must be done before parent constructor which calls #setDisabled) this.dropdownWidget = new OO.ui.DropdownWidget(); // Parent constructor OO.ui.DropdownInputWidget.super.call( this, config ); // Events this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } ); // Initialization this.setOptions( config.options || [] ); this.$element .addClass( 'oo-ui-dropdownInputWidget' ) .append( this.dropdownWidget.$element ); }; /* Setup */ OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget ); /* Methods */ /** * @inheritdoc * @private */ OO.ui.DropdownInputWidget.prototype.getInputElement = function () { return $( '<input type="hidden">' ); }; /** * Handles menu select events. * * @private * @param {OO.ui.MenuOptionWidget} item Selected menu item */ OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) { this.setValue( item.getData() ); }; /** * @inheritdoc */ OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) { var item = this.dropdownWidget.getMenu().getItemFromData( value ); if ( item ) { this.dropdownWidget.getMenu().selectItem( item ); } OO.ui.DropdownInputWidget.super.prototype.setValue.call( this, value ); return this; }; /** * @inheritdoc */ OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) { this.dropdownWidget.setDisabled( state ); OO.ui.DropdownInputWidget.super.prototype.setDisabled.call( this, state ); return this; }; /** * Set the options available for this input. * * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }` * @chainable */ OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) { var value = this.getValue(); // Rebuild the dropdown menu this.dropdownWidget.getMenu() .clearItems() .addItems( options.map( function ( opt ) { return new OO.ui.MenuOptionWidget( { data: opt.data, label: opt.label !== undefined ? opt.label : opt.data } ); } ) ); // Restore the previous value, or reset to something sensible if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) { // Previous value is still available, ensure consistency with the dropdown this.setValue( value ); } else { // No longer valid, reset if ( options.length ) { this.setValue( options[ 0 ].data ); } } return this; }; /** * @inheritdoc */ OO.ui.DropdownInputWidget.prototype.focus = function () { this.dropdownWidget.getMenu().toggle( true ); return this; }; /** * @inheritdoc */ OO.ui.DropdownInputWidget.prototype.blur = function () { this.dropdownWidget.getMenu().toggle( false ); return this; }; /** * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set, * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select} * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information, * please see the [OOjs UI documentation on MediaWiki][1]. * * @example * // An example of selected, unselected, and disabled radio inputs * var radio1 = new OO.ui.RadioInputWidget( { * value: 'a', * selected: true * } ); * var radio2 = new OO.ui.RadioInputWidget( { * value: 'b' * } ); * var radio3 = new OO.ui.RadioInputWidget( { * value: 'c', * disabled: true * } ); * // Create a fieldset layout with fields for each radio button. * var fieldset = new OO.ui.FieldsetLayout( { * label: 'Radio inputs' * } ); * fieldset.addItems( [ * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ), * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ), * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ), * ] ); * $( 'body' ).append( fieldset.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs * * @class * @extends OO.ui.InputWidget * * @constructor * @param {Object} [config] Configuration options * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected. */ OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.RadioInputWidget.super.call( this, config ); // Initialization this.$element.addClass( 'oo-ui-radioInputWidget' ); this.setSelected( config.selected !== undefined ? config.selected : false ); }; /* Setup */ OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget ); /* Methods */ /** * @inheritdoc * @private */ OO.ui.RadioInputWidget.prototype.getInputElement = function () { return $( '<input type="radio" />' ); }; /** * @inheritdoc */ OO.ui.RadioInputWidget.prototype.onEdit = function () { // RadioInputWidget doesn't track its state. }; /** * Set selection state of this radio button. * * @param {boolean} state `true` for selected * @chainable */ OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) { // RadioInputWidget doesn't track its state. this.$input.prop( 'checked', state ); return this; }; /** * Check if this radio button is selected. * * @return {boolean} Radio is selected */ OO.ui.RadioInputWidget.prototype.isSelected = function () { return this.$input.prop( 'checked' ); }; /** * TextInputWidgets, like HTML text inputs, can be configured with options that customize the * size of the field as well as its presentation. In addition, these widgets can be configured * with {@link OO.ui.IconElement icons}, {@link OO.ui.IndicatorElement indicators}, an optional * validation-pattern (used to determine if an input value is valid or not) and an input filter, * which modifies incoming values rather than validating them. * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples. * * @example * // Example of a text input widget * var textInput = new OO.ui.TextInputWidget( { * value: 'Text input' * } ) * $( 'body' ).append( textInput.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs * * @class * @extends OO.ui.InputWidget * @mixins OO.ui.IconElement * @mixins OO.ui.IndicatorElement * @mixins OO.ui.PendingElement * @mixins OO.ui.LabelElement * * @constructor * @param {Object} [config] Configuration options * @cfg {string} [type='text'] The value of the HTML `type` attribute * @cfg {string} [placeholder] Placeholder text * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to * instruct the browser to focus this widget. * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input. * @cfg {number} [maxLength] Maximum number of characters allowed in the input. * @cfg {boolean} [multiline=false] Allow multiple lines of text * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content. * Use the #maxRows config to specify a maximum number of displayed rows. * @cfg {boolean} [maxRows=10] Maximum number of rows to display when #autosize is set to true. * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of * the value or placeholder text: `'before'` or `'after'` * @cfg {boolean} [required=false] Mark the field as required * @cfg {RegExp|string} [validate] Validation pattern, either a regular expression or the * symbolic name of a pattern defined by the class: 'non-empty' (the value cannot be an empty string) * or 'integer' (the value must contain only numbers). */ OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) { // Configuration initialization config = $.extend( { type: 'text', labelPosition: 'after', maxRows: 10 }, config ); // Parent constructor OO.ui.TextInputWidget.super.call( this, config ); // Mixin constructors OO.ui.IconElement.call( this, config ); OO.ui.IndicatorElement.call( this, config ); OO.ui.PendingElement.call( this, config ); OO.ui.LabelElement.call( this, config ); // Properties this.readOnly = false; this.multiline = !!config.multiline; this.autosize = !!config.autosize; this.maxRows = config.maxRows; this.validate = null; // Clone for resizing if ( this.autosize ) { this.$clone = this.$input .clone() .insertAfter( this.$input ) .attr( 'aria-hidden', 'true' ) .addClass( 'oo-ui-element-hidden' ); } this.setValidation( config.validate ); this.setLabelPosition( config.labelPosition ); // Events this.$input.on( { keypress: this.onKeyPress.bind( this ), blur: this.setValidityFlag.bind( this ) } ); this.$input.one( { focus: this.onElementAttach.bind( this ) } ); this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) ); this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) ); this.on( 'labelChange', this.updatePosition.bind( this ) ); // Initialization this.$element .addClass( 'oo-ui-textInputWidget' ) .append( this.$icon, this.$indicator ); this.setReadOnly( !!config.readOnly ); if ( config.placeholder ) { this.$input.attr( 'placeholder', config.placeholder ); } if ( config.maxLength !== undefined ) { this.$input.attr( 'maxlength', config.maxLength ); } if ( config.autofocus ) { this.$input.attr( 'autofocus', 'autofocus' ); } if ( config.required ) { this.$input.attr( 'required', 'true' ); } if ( this.label || config.autosize ) { this.installParentChangeDetector(); } }; /* Setup */ OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget ); OO.mixinClass( OO.ui.TextInputWidget, OO.ui.IconElement ); OO.mixinClass( OO.ui.TextInputWidget, OO.ui.IndicatorElement ); OO.mixinClass( OO.ui.TextInputWidget, OO.ui.PendingElement ); OO.mixinClass( OO.ui.TextInputWidget, OO.ui.LabelElement ); /* Static properties */ OO.ui.TextInputWidget.static.validationPatterns = { 'non-empty': /.+/, integer: /^\d+$/ }; /* Events */ /** * An `enter` event is emitted when the user presses 'enter' inside the text box. * * Not emitted if the input is multiline. * * @event enter */ /* Methods */ /** * Handle icon mouse down events. * * @private * @param {jQuery.Event} e Mouse down event * @fires icon */ OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) { if ( e.which === 1 ) { this.$input[ 0 ].focus(); return false; } }; /** * Handle indicator mouse down events. * * @private * @param {jQuery.Event} e Mouse down event * @fires indicator */ OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) { if ( e.which === 1 ) { this.$input[ 0 ].focus(); return false; } }; /** * Handle key press events. * * @private * @param {jQuery.Event} e Key press event * @fires enter If enter key is pressed and input is not multiline */ OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) { if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) { this.emit( 'enter', e ); } }; /** * Handle element attach events. * * @private * @param {jQuery.Event} e Element attach event */ OO.ui.TextInputWidget.prototype.onElementAttach = function () { // Any previously calculated size is now probably invalid if we reattached elsewhere this.valCache = null; this.adjustSize(); this.positionLabel(); }; /** * @inheritdoc */ OO.ui.TextInputWidget.prototype.onEdit = function () { this.adjustSize(); // Parent method return OO.ui.TextInputWidget.super.prototype.onEdit.call( this ); }; /** * @inheritdoc */ OO.ui.TextInputWidget.prototype.setValue = function ( value ) { // Parent method OO.ui.TextInputWidget.super.prototype.setValue.call( this, value ); this.setValidityFlag(); this.adjustSize(); return this; }; /** * Check if the input is {@link #readOnly read-only}. * * @return {boolean} */ OO.ui.TextInputWidget.prototype.isReadOnly = function () { return this.readOnly; }; /** * Set the {@link #readOnly read-only} state of the input. * * @param {boolean} state Make input read-only * @chainable */ OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) { this.readOnly = !!state; this.$input.prop( 'readOnly', this.readOnly ); return this; }; /** * Support function for making #onElementAttach work across browsers. * * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback. * * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the * first time that the element gets attached to the documented. */ OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () { var mutationObserver, onRemove, topmostNode, fakeParentNode, MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver, widget = this; if ( MutationObserver ) { // The new way. If only it wasn't so ugly. if ( this.$element.closest( 'html' ).length ) { // Widget is attached already, do nothing. This breaks the functionality of this function when // the widget is detached and reattached. Alas, doing this correctly with MutationObserver // would require observation of the whole document, which would hurt performance of other, // more important code. return; } // Find topmost node in the tree topmostNode = this.$element[0]; while ( topmostNode.parentNode ) { topmostNode = topmostNode.parentNode; } // We have no way to detect the $element being attached somewhere without observing the entire // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the // parent node of $element, and instead detect when $element is removed from it (and thus // probably attached somewhere else). If there is no parent, we create a "fake" one. If it // doesn't get attached, we end up back here and create the parent. mutationObserver = new MutationObserver( function ( mutations ) { var i, j, removedNodes; for ( i = 0; i < mutations.length; i++ ) { removedNodes = mutations[ i ].removedNodes; for ( j = 0; j < removedNodes.length; j++ ) { if ( removedNodes[ j ] === topmostNode ) { setTimeout( onRemove, 0 ); return; } } } } ); onRemove = function () { // If the node was attached somewhere else, report it if ( widget.$element.closest( 'html' ).length ) { widget.onElementAttach(); } mutationObserver.disconnect(); widget.installParentChangeDetector(); }; // Create a fake parent and observe it fakeParentNode = $( '<div>' ).append( this.$element )[0]; mutationObserver.observe( fakeParentNode, { childList: true } ); } else { // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated. this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) ); } }; /** * Automatically adjust the size of the text input. * * This only affects #multiline inputs that are {@link #autosize autosized}. * * @chainable */ OO.ui.TextInputWidget.prototype.adjustSize = function () { var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError, idealHeight; if ( this.multiline && this.autosize && this.$input.val() !== this.valCache ) { this.$clone .val( this.$input.val() ) .attr( 'rows', '' ) // Set inline height property to 0 to measure scroll height .css( 'height', 0 ); this.$clone.removeClass( 'oo-ui-element-hidden' ); this.valCache = this.$input.val(); scrollHeight = this.$clone[ 0 ].scrollHeight; // Remove inline height property to measure natural heights this.$clone.css( 'height', '' ); innerHeight = this.$clone.innerHeight(); outerHeight = this.$clone.outerHeight(); // Measure max rows height this.$clone .attr( 'rows', this.maxRows ) .css( 'height', 'auto' ) .val( '' ); maxInnerHeight = this.$clone.innerHeight(); // Difference between reported innerHeight and scrollHeight with no scrollbars present // Equals 1 on Blink-based browsers and 0 everywhere else measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight; idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError ); this.$clone.addClass( 'oo-ui-element-hidden' ); // Only apply inline height when expansion beyond natural height is needed if ( idealHeight > innerHeight ) { // Use the difference between the inner and outer height as a buffer this.$input.css( 'height', idealHeight + ( outerHeight - innerHeight ) ); } else { this.$input.css( 'height', '' ); } } return this; }; /** * @inheritdoc * @private */ OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) { return config.multiline ? $( '<textarea>' ) : $( '<input type="' + config.type + '" />' ); }; /** * Check if the input supports multiple lines. * * @return {boolean} */ OO.ui.TextInputWidget.prototype.isMultiline = function () { return !!this.multiline; }; /** * Check if the input automatically adjusts its size. * * @return {boolean} */ OO.ui.TextInputWidget.prototype.isAutosizing = function () { return !!this.autosize; }; /** * Select the entire text of the input. * * @chainable */ OO.ui.TextInputWidget.prototype.select = function () { this.$input.select(); return this; }; /** * Set the validation pattern. * * The validation pattern is either a regular expression or the symbolic name of a pattern * defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the * value must contain only numbers). * * @param {RegExp|string|null} validate Regular expression or the symbolic name of a * pattern (either ‘integer’ or ‘non-empty’) defined by the class. */ OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) { if ( validate instanceof RegExp ) { this.validate = validate; } else { this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/; } }; /** * Sets the 'invalid' flag appropriately. */ OO.ui.TextInputWidget.prototype.setValidityFlag = function () { var widget = this; this.isValid().done( function ( valid ) { widget.setFlags( { invalid: !valid } ); } ); }; /** * Check if a value is valid. * * This method returns a promise that resolves with a boolean `true` if the current value is * considered valid according to the supplied {@link #validate validation pattern}. * * @return {jQuery.Deferred} A promise that resolves to a boolean `true` if the value is valid. */ OO.ui.TextInputWidget.prototype.isValid = function () { return $.Deferred().resolve( !!this.getValue().match( this.validate ) ).promise(); }; /** * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`. * * @param {string} labelPosition Label position, 'before' or 'after' * @chainable */ OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) { this.labelPosition = labelPosition; this.updatePosition(); return this; }; /** * Deprecated alias of #setLabelPosition * * @deprecated Use setLabelPosition instead. */ OO.ui.TextInputWidget.prototype.setPosition = OO.ui.TextInputWidget.prototype.setLabelPosition; /** * Update the position of the inline label. * * This method is called by #setLabelPosition, and can also be called on its own if * something causes the label to be mispositioned. * * * @chainable */ OO.ui.TextInputWidget.prototype.updatePosition = function () { var after = this.labelPosition === 'after'; this.$element .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after ) .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after ); if ( this.label ) { this.positionLabel(); } return this; }; /** * Position the label by setting the correct padding on the input. * * @private * @chainable */ OO.ui.TextInputWidget.prototype.positionLabel = function () { // Clear old values this.$input // Clear old values if present .css( { 'padding-right': '', 'padding-left': '' } ); if ( this.label ) { this.$element.append( this.$label ); } else { this.$label.detach(); return; } var after = this.labelPosition === 'after', rtl = this.$element.css( 'direction' ) === 'rtl', property = after === rtl ? 'padding-left' : 'padding-right'; this.$input.css( property, this.$label.outerWidth( true ) ); return this; }; /** * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which * a value can be chosen instead). Users can choose options from the combo box in one of two ways: * * - by typing a value in the text input field. If the value exactly matches the value of a menu * option, that option will appear to be selected. * - by choosing a value from the menu. The value of the chosen option will then appear in the text * input field. * * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1]. * * @example * // Example: A ComboBoxWidget. * var comboBox = new OO.ui.ComboBoxWidget( { * label: 'ComboBoxWidget', * input: { value: 'Option One' }, * menu: { * items: [ * new OO.ui.MenuOptionWidget( { * data: 'Option 1', * label: 'Option One' * } ), * new OO.ui.MenuOptionWidget( { * data: 'Option 2', * label: 'Option Two' * } ), * new OO.ui.MenuOptionWidget( { * data: 'Option 3', * label: 'Option Three' * } ), * new OO.ui.MenuOptionWidget( { * data: 'Option 4', * label: 'Option Four' * } ), * new OO.ui.MenuOptionWidget( { * data: 'Option 5', * label: 'Option Five' * } ) * ] * } * } ); * $( 'body' ).append( comboBox.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options * * @class * @extends OO.ui.Widget * @mixins OO.ui.TabIndexedElement * * @constructor * @param {Object} [config] Configuration options * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}. * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}. * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the * containing `<div>` and has a larger area. By default, the menu uses relative positioning. */ OO.ui.ComboBoxWidget = function OoUiComboBoxWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.ComboBoxWidget.super.call( this, config ); // Properties (must be set before TabIndexedElement constructor call) this.$indicator = this.$( '<span>' ); // Mixin constructors OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) ); // Properties this.$overlay = config.$overlay || this.$element; this.input = new OO.ui.TextInputWidget( $.extend( { indicator: 'down', $indicator: this.$indicator, disabled: this.isDisabled() }, config.input ) ); this.input.$input.eq( 0 ).attr( { role: 'combobox', 'aria-autocomplete': 'list' } ); this.menu = new OO.ui.TextInputMenuSelectWidget( this.input, $.extend( { widget: this, input: this.input, disabled: this.isDisabled() }, config.menu ) ); // Events this.$indicator.on( { click: this.onClick.bind( this ), keypress: this.onKeyPress.bind( this ) } ); this.input.connect( this, { change: 'onInputChange', enter: 'onInputEnter' } ); this.menu.connect( this, { choose: 'onMenuChoose', add: 'onMenuItemsChange', remove: 'onMenuItemsChange' } ); // Initialization this.$element.addClass( 'oo-ui-comboBoxWidget' ).append( this.input.$element ); this.$overlay.append( this.menu.$element ); this.onMenuItemsChange(); }; /* Setup */ OO.inheritClass( OO.ui.ComboBoxWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.ComboBoxWidget, OO.ui.TabIndexedElement ); /* Methods */ /** * Get the combobox's menu. * @return {OO.ui.TextInputMenuSelectWidget} Menu widget */ OO.ui.ComboBoxWidget.prototype.getMenu = function () { return this.menu; }; /** * Handle input change events. * * @private * @param {string} value New value */ OO.ui.ComboBoxWidget.prototype.onInputChange = function ( value ) { var match = this.menu.getItemFromData( value ); this.menu.selectItem( match ); if ( this.menu.getHighlightedItem() ) { this.menu.highlightItem( match ); } if ( !this.isDisabled() ) { this.menu.toggle( true ); } }; /** * Handle mouse click events. * * * @private * @param {jQuery.Event} e Mouse click event */ OO.ui.ComboBoxWidget.prototype.onClick = function ( e ) { if ( !this.isDisabled() && e.which === 1 ) { this.menu.toggle(); this.input.$input[ 0 ].focus(); } return false; }; /** * Handle key press events. * * * @private * @param {jQuery.Event} e Key press event */ OO.ui.ComboBoxWidget.prototype.onKeyPress = function ( e ) { if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) { this.menu.toggle(); this.input.$input[ 0 ].focus(); return false; } }; /** * Handle input enter events. * * @private */ OO.ui.ComboBoxWidget.prototype.onInputEnter = function () { if ( !this.isDisabled() ) { this.menu.toggle( false ); } }; /** * Handle menu choose events. * * @private * @param {OO.ui.OptionWidget} item Chosen item */ OO.ui.ComboBoxWidget.prototype.onMenuChoose = function ( item ) { if ( item ) { this.input.setValue( item.getData() ); } }; /** * Handle menu item change events. * * @private */ OO.ui.ComboBoxWidget.prototype.onMenuItemsChange = function () { var match = this.menu.getItemFromData( this.input.getValue() ); this.menu.selectItem( match ); if ( this.menu.getHighlightedItem() ) { this.menu.highlightItem( match ); } this.$element.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu.isEmpty() ); }; /** * @inheritdoc */ OO.ui.ComboBoxWidget.prototype.setDisabled = function ( disabled ) { // Parent method OO.ui.ComboBoxWidget.super.prototype.setDisabled.call( this, disabled ); if ( this.input ) { this.input.setDisabled( this.isDisabled() ); } if ( this.menu ) { this.menu.setDisabled( this.isDisabled() ); } return this; }; /** * LabelWidgets help identify the function of interface elements. Each LabelWidget can * be configured with a `label` option that is set to a string, a label node, or a function: * * - String: a plaintext string * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a * label that includes a link or special styling, such as a gray color or additional graphical elements. * - Function: a function that will produce a string in the future. Functions are used * in cases where the value of the label is not currently defined. * * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which * will come into focus when the label is clicked. * * @example * // Examples of LabelWidgets * var label1 = new OO.ui.LabelWidget( { * label: 'plaintext label' * } ); * var label2 = new OO.ui.LabelWidget( { * label: $( '<a href="default.html">jQuery label</a>' ) * } ); * // Create a fieldset layout with fields for each example * var fieldset = new OO.ui.FieldsetLayout(); * fieldset.addItems( [ * new OO.ui.FieldLayout( label1 ), * new OO.ui.FieldLayout( label2 ) * ] ); * $( 'body' ).append( fieldset.$element ); * * * @class * @extends OO.ui.Widget * @mixins OO.ui.LabelElement * * @constructor * @param {Object} [config] Configuration options * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label. * Clicking the label will focus the specified input field. */ OO.ui.LabelWidget = function OoUiLabelWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.LabelWidget.super.call( this, config ); // Mixin constructors OO.ui.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) ); OO.ui.TitledElement.call( this, config ); // Properties this.input = config.input; // Events if ( this.input instanceof OO.ui.InputWidget ) { this.$element.on( 'click', this.onClick.bind( this ) ); } // Initialization this.$element.addClass( 'oo-ui-labelWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.LabelWidget, OO.ui.LabelElement ); OO.mixinClass( OO.ui.LabelWidget, OO.ui.TitledElement ); /* Static Properties */ OO.ui.LabelWidget.static.tagName = 'span'; /* Methods */ /** * Handles label mouse click events. * * @private * @param {jQuery.Event} e Mouse click event */ OO.ui.LabelWidget.prototype.onClick = function () { this.input.simulateLabelClick(); return false; }; /** * OptionWidgets are special elements that can be selected and configured with data. The * data is often unique for each option, but it does not have to be. OptionWidgets are used * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information * and examples, please see the [OOjs UI documentation on MediaWiki][1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options * * @class * @extends OO.ui.Widget * @mixins OO.ui.LabelElement * @mixins OO.ui.FlaggedElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.OptionWidget = function OoUiOptionWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.OptionWidget.super.call( this, config ); // Mixin constructors OO.ui.ItemWidget.call( this ); OO.ui.LabelElement.call( this, config ); OO.ui.FlaggedElement.call( this, config ); // Properties this.selected = false; this.highlighted = false; this.pressed = false; // Initialization this.$element .data( 'oo-ui-optionWidget', this ) .attr( 'role', 'option' ) .addClass( 'oo-ui-optionWidget' ) .append( this.$label ); }; /* Setup */ OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.OptionWidget, OO.ui.ItemWidget ); OO.mixinClass( OO.ui.OptionWidget, OO.ui.LabelElement ); OO.mixinClass( OO.ui.OptionWidget, OO.ui.FlaggedElement ); /* Static Properties */ OO.ui.OptionWidget.static.selectable = true; OO.ui.OptionWidget.static.highlightable = true; OO.ui.OptionWidget.static.pressable = true; OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false; /* Methods */ /** * Check if the option can be selected. * * @return {boolean} Item is selectable */ OO.ui.OptionWidget.prototype.isSelectable = function () { return this.constructor.static.selectable && !this.isDisabled(); }; /** * Check if the option can be highlighted. A highlight indicates that the option * may be selected when a user presses enter or clicks. Disabled items cannot * be highlighted. * * @return {boolean} Item is highlightable */ OO.ui.OptionWidget.prototype.isHighlightable = function () { return this.constructor.static.highlightable && !this.isDisabled(); }; /** * Check if the option can be pressed. The pressed state occurs when a user mouses * down on an item, but has not yet let go of the mouse. * * @return {boolean} Item is pressable */ OO.ui.OptionWidget.prototype.isPressable = function () { return this.constructor.static.pressable && !this.isDisabled(); }; /** * Check if the option is selected. * * @return {boolean} Item is selected */ OO.ui.OptionWidget.prototype.isSelected = function () { return this.selected; }; /** * Check if the option is highlighted. A highlight indicates that the * item may be selected when a user presses enter or clicks. * * @return {boolean} Item is highlighted */ OO.ui.OptionWidget.prototype.isHighlighted = function () { return this.highlighted; }; /** * Check if the option is pressed. The pressed state occurs when a user mouses * down on an item, but has not yet let go of the mouse. The item may appear * selected, but it will not be selected until the user releases the mouse. * * @return {boolean} Item is pressed */ OO.ui.OptionWidget.prototype.isPressed = function () { return this.pressed; }; /** * Set the option’s selected state. In general, all modifications to the selection * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )} * method instead of this method. * * @param {boolean} [state=false] Select option * @chainable */ OO.ui.OptionWidget.prototype.setSelected = function ( state ) { if ( this.constructor.static.selectable ) { this.selected = !!state; this.$element .toggleClass( 'oo-ui-optionWidget-selected', state ) .attr( 'aria-selected', state.toString() ); if ( state && this.constructor.static.scrollIntoViewOnSelect ) { this.scrollElementIntoView(); } this.updateThemeClasses(); } return this; }; /** * Set the option’s highlighted state. In general, all programmatic * modifications to the highlight should be handled by the * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )} * method instead of this method. * * @param {boolean} [state=false] Highlight option * @chainable */ OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) { if ( this.constructor.static.highlightable ) { this.highlighted = !!state; this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state ); this.updateThemeClasses(); } return this; }; /** * Set the option’s pressed state. In general, all * programmatic modifications to the pressed state should be handled by the * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )} * method instead of this method. * * @param {boolean} [state=false] Press option * @chainable */ OO.ui.OptionWidget.prototype.setPressed = function ( state ) { if ( this.constructor.static.pressable ) { this.pressed = !!state; this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state ); this.updateThemeClasses(); } return this; }; /** * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured * with an {@link OO.ui.IconElement icon} and/or {@link OO.ui.IndicatorElement indicator}. * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive * options. For more information about options and selects, please see the * [OOjs UI documentation on MediaWiki][1]. * * @example * // Decorated options in a select widget * var select = new OO.ui.SelectWidget( { * items: [ * new OO.ui.DecoratedOptionWidget( { * data: 'a', * label: 'Option with icon', * icon: 'help' * } ), * new OO.ui.DecoratedOptionWidget( { * data: 'b', * label: 'Option with indicator', * indicator: 'next' * } ) * ] * } ); * $( 'body' ).append( select.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options * * @class * @extends OO.ui.OptionWidget * @mixins OO.ui.IconElement * @mixins OO.ui.IndicatorElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) { // Parent constructor OO.ui.DecoratedOptionWidget.super.call( this, config ); // Mixin constructors OO.ui.IconElement.call( this, config ); OO.ui.IndicatorElement.call( this, config ); // Initialization this.$element .addClass( 'oo-ui-decoratedOptionWidget' ) .prepend( this.$icon ) .append( this.$indicator ); }; /* Setup */ OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget ); OO.mixinClass( OO.ui.OptionWidget, OO.ui.IconElement ); OO.mixinClass( OO.ui.OptionWidget, OO.ui.IndicatorElement ); /** * ButtonOptionWidget is a special type of {@link OO.ui.ButtonElement button element} that * can be selected and configured with data. The class is * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the * [OOjs UI documentation on MediaWiki] [1] for more information. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options * * @class * @extends OO.ui.DecoratedOptionWidget * @mixins OO.ui.ButtonElement * @mixins OO.ui.TabIndexedElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) { // Configuration initialization config = $.extend( { tabIndex: -1 }, config ); // Parent constructor OO.ui.ButtonOptionWidget.super.call( this, config ); // Mixin constructors OO.ui.ButtonElement.call( this, config ); OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) ); // Initialization this.$element.addClass( 'oo-ui-buttonOptionWidget' ); this.$button.append( this.$element.contents() ); this.$element.append( this.$button ); }; /* Setup */ OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget ); OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.ButtonElement ); OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.TabIndexedElement ); /* Static Properties */ // Allow button mouse down events to pass through so they can be handled by the parent select widget OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false; OO.ui.ButtonOptionWidget.static.highlightable = false; /* Methods */ /** * @inheritdoc */ OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) { OO.ui.ButtonOptionWidget.super.prototype.setSelected.call( this, state ); if ( this.constructor.static.selectable ) { this.setActive( state ); } return this; }; /** * RadioOptionWidget is an option widget that looks like a radio button. * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options. * Please see the [OOjs UI documentation on MediaWiki] [1] for more information. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option * * @class * @extends OO.ui.OptionWidget * * @constructor * @param {Object} [config] Configuration options */ OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) { // Configuration initialization config = config || {}; // Properties (must be done before parent constructor which calls #setDisabled) this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } ); // Parent constructor OO.ui.RadioOptionWidget.super.call( this, config ); // Initialization this.$element .addClass( 'oo-ui-radioOptionWidget' ) .prepend( this.radio.$element ); }; /* Setup */ OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget ); /* Static Properties */ OO.ui.RadioOptionWidget.static.highlightable = false; OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true; OO.ui.RadioOptionWidget.static.pressable = false; OO.ui.RadioOptionWidget.static.tagName = 'label'; /* Methods */ /** * @inheritdoc */ OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) { OO.ui.RadioOptionWidget.super.prototype.setSelected.call( this, state ); this.radio.setSelected( state ); return this; }; /** * @inheritdoc */ OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) { OO.ui.RadioOptionWidget.super.prototype.setDisabled.call( this, disabled ); this.radio.setDisabled( this.isDisabled() ); return this; }; /** * MenuOptionWidget is an option widget that looks like a menu item. The class is used with * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see * the [OOjs UI documentation on MediaWiki] [1] for more information. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options * * @class * @extends OO.ui.DecoratedOptionWidget * * @constructor * @param {Object} [config] Configuration options */ OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) { // Configuration initialization config = $.extend( { icon: 'check' }, config ); // Parent constructor OO.ui.MenuOptionWidget.super.call( this, config ); // Initialization this.$element .attr( 'role', 'menuitem' ) .addClass( 'oo-ui-menuOptionWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget ); /* Static Properties */ OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true; /** * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected. * * @example * var myDropdown = new OO.ui.DropdownWidget( { * menu: { * items: [ * new OO.ui.MenuSectionOptionWidget( { * label: 'Dogs' * } ), * new OO.ui.MenuOptionWidget( { * data: 'corgi', * label: 'Welsh Corgi' * } ), * new OO.ui.MenuOptionWidget( { * data: 'poodle', * label: 'Standard Poodle' * } ), * new OO.ui.MenuSectionOptionWidget( { * label: 'Cats' * } ), * new OO.ui.MenuOptionWidget( { * data: 'lion', * label: 'Lion' * } ) * ] * } * } ); * $( 'body' ).append( myDropdown.$element ); * * * @class * @extends OO.ui.DecoratedOptionWidget * * @constructor * @param {Object} [config] Configuration options */ OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) { // Parent constructor OO.ui.MenuSectionOptionWidget.super.call( this, config ); // Initialization this.$element.addClass( 'oo-ui-menuSectionOptionWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget ); /* Static Properties */ OO.ui.MenuSectionOptionWidget.static.selectable = false; OO.ui.MenuSectionOptionWidget.static.highlightable = false; /** * Items for an OO.ui.OutlineSelectWidget. * * @class * @extends OO.ui.DecoratedOptionWidget * * @constructor * @param {Object} [config] Configuration options * @cfg {number} [level] Indentation level * @cfg {boolean} [movable] Allow modification from outline controls */ OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.OutlineOptionWidget.super.call( this, config ); // Properties this.level = 0; this.movable = !!config.movable; this.removable = !!config.removable; // Initialization this.$element.addClass( 'oo-ui-outlineOptionWidget' ); this.setLevel( config.level ); }; /* Setup */ OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget ); /* Static Properties */ OO.ui.OutlineOptionWidget.static.highlightable = false; OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true; OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-'; OO.ui.OutlineOptionWidget.static.levels = 3; /* Methods */ /** * Check if item is movable. * * Movability is used by outline controls. * * @return {boolean} Item is movable */ OO.ui.OutlineOptionWidget.prototype.isMovable = function () { return this.movable; }; /** * Check if item is removable. * * Removability is used by outline controls. * * @return {boolean} Item is removable */ OO.ui.OutlineOptionWidget.prototype.isRemovable = function () { return this.removable; }; /** * Get indentation level. * * @return {number} Indentation level */ OO.ui.OutlineOptionWidget.prototype.getLevel = function () { return this.level; }; /** * Set movability. * * Movability is used by outline controls. * * @param {boolean} movable Item is movable * @chainable */ OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) { this.movable = !!movable; this.updateThemeClasses(); return this; }; /** * Set removability. * * Removability is used by outline controls. * * @param {boolean} movable Item is removable * @chainable */ OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) { this.removable = !!removable; this.updateThemeClasses(); return this; }; /** * Set indentation level. * * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel] * @chainable */ OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) { var levels = this.constructor.static.levels, levelClass = this.constructor.static.levelClass, i = levels; this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0; while ( i-- ) { if ( this.level === i ) { this.$element.addClass( levelClass + i ); } else { this.$element.removeClass( levelClass + i ); } } this.updateThemeClasses(); return this; }; /** * PopupWidget is a container for content. The popup is overlaid and positioned absolutely. * By default, each popup has an anchor that points toward its origin. * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples. * * @example * // A popup widget. * var popup = new OO.ui.PopupWidget( { * $content: $( '<p>Hi there!</p>' ), * padded: true, * width: 300 * } ); * * $( 'body' ).append( popup.$element ); * // To display the popup, toggle the visibility to 'true'. * popup.toggle( true ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups * * @class * @extends OO.ui.Widget * @mixins OO.ui.LabelElement * * @constructor * @param {Object} [config] Configuration options * @cfg {number} [width=320] Width of popup in pixels * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height. * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup * @cfg {string} [align='center'] Alignment of the popup: `center`, `left`, or `right`. * If the popup is right-aligned, the right edge of the popup is aligned to the anchor. * For left-aligned popups, the left edge is aligned to the anchor. * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container. * See the [OOjs UI docs on MediaWiki][3] for an example. * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels. * @cfg {jQuery} [$content] Content to append to the popup's body * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus. * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked. * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2] * for an example. * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close * button. * @cfg {boolean} [padded] Add padding to the popup's body */ OO.ui.PopupWidget = function OoUiPopupWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.PopupWidget.super.call( this, config ); // Properties (must be set before ClippableElement constructor call) this.$body = $( '<div>' ); // Mixin constructors OO.ui.LabelElement.call( this, config ); OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$body } ) ); // Properties this.$popup = $( '<div>' ); this.$head = $( '<div>' ); this.$anchor = $( '<div>' ); // If undefined, will be computed lazily in updateDimensions() this.$container = config.$container; this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10; this.autoClose = !!config.autoClose; this.$autoCloseIgnore = config.$autoCloseIgnore; this.transitionTimeout = null; this.anchor = null; this.width = config.width !== undefined ? config.width : 320; this.height = config.height !== undefined ? config.height : null; this.align = config.align || 'center'; this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } ); this.onMouseDownHandler = this.onMouseDown.bind( this ); this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this ); // Events this.closeButton.connect( this, { click: 'onCloseButtonClick' } ); // Initialization this.toggleAnchor( config.anchor === undefined || config.anchor ); this.$body.addClass( 'oo-ui-popupWidget-body' ); this.$anchor.addClass( 'oo-ui-popupWidget-anchor' ); this.$head .addClass( 'oo-ui-popupWidget-head' ) .append( this.$label, this.closeButton.$element ); if ( !config.head ) { this.$head.addClass( 'oo-ui-element-hidden' ); } this.$popup .addClass( 'oo-ui-popupWidget-popup' ) .append( this.$head, this.$body ); this.$element .addClass( 'oo-ui-popupWidget' ) .append( this.$popup, this.$anchor ); // Move content, which was added to #$element by OO.ui.Widget, to the body if ( config.$content instanceof jQuery ) { this.$body.append( config.$content ); } if ( config.padded ) { this.$body.addClass( 'oo-ui-popupWidget-body-padded' ); } // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods // that reference properties not initialized at that time of parent class construction // TODO: Find a better way to handle post-constructor setup this.visible = false; this.$element.addClass( 'oo-ui-element-hidden' ); }; /* Setup */ OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.PopupWidget, OO.ui.LabelElement ); OO.mixinClass( OO.ui.PopupWidget, OO.ui.ClippableElement ); /* Methods */ /** * Handles mouse down events. * * @private * @param {MouseEvent} e Mouse down event */ OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) { if ( this.isVisible() && !$.contains( this.$element[ 0 ], e.target ) && ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length ) ) { this.toggle( false ); } }; /** * Bind mouse down listener. * * @private */ OO.ui.PopupWidget.prototype.bindMouseDownListener = function () { // Capture clicks outside popup this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler, true ); }; /** * Handles close button click events. * * @private */ OO.ui.PopupWidget.prototype.onCloseButtonClick = function () { if ( this.isVisible() ) { this.toggle( false ); } }; /** * Unbind mouse down listener. * * @private */ OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () { this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler, true ); }; /** * Handles key down events. * * @private * @param {KeyboardEvent} e Key down event */ OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) { if ( e.which === OO.ui.Keys.ESCAPE && this.isVisible() ) { this.toggle( false ); e.preventDefault(); e.stopPropagation(); } }; /** * Bind key down listener. * * @private */ OO.ui.PopupWidget.prototype.bindKeyDownListener = function () { this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true ); }; /** * Unbind key down listener. * * @private */ OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () { this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true ); }; /** * Show, hide, or toggle the visibility of the anchor. * * @param {boolean} [show] Show anchor, omit to toggle */ OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) { show = show === undefined ? !this.anchored : !!show; if ( this.anchored !== show ) { if ( show ) { this.$element.addClass( 'oo-ui-popupWidget-anchored' ); } else { this.$element.removeClass( 'oo-ui-popupWidget-anchored' ); } this.anchored = show; } }; /** * Check if the anchor is visible. * * @return {boolean} Anchor is visible */ OO.ui.PopupWidget.prototype.hasAnchor = function () { return this.anchor; }; /** * @inheritdoc */ OO.ui.PopupWidget.prototype.toggle = function ( show ) { show = show === undefined ? !this.isVisible() : !!show; var change = show !== this.isVisible(); // Parent method OO.ui.PopupWidget.super.prototype.toggle.call( this, show ); if ( change ) { if ( show ) { if ( this.autoClose ) { this.bindMouseDownListener(); this.bindKeyDownListener(); } this.updateDimensions(); this.toggleClipping( true ); } else { this.toggleClipping( false ); if ( this.autoClose ) { this.unbindMouseDownListener(); this.unbindKeyDownListener(); } } } return this; }; /** * Set the size of the popup. * * Changing the size may also change the popup's position depending on the alignment. * * @param {number} width Width in pixels * @param {number} height Height in pixels * @param {boolean} [transition=false] Use a smooth transition * @chainable */ OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) { this.width = width; this.height = height !== undefined ? height : null; if ( this.isVisible() ) { this.updateDimensions( transition ); } }; /** * Update the size and position. * * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will * be called automatically. * * @param {boolean} [transition=false] Use a smooth transition * @chainable */ OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) { var popupOffset, originOffset, containerLeft, containerWidth, containerRight, popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth, widget = this; if ( !this.$container ) { // Lazy-initialize $container if not specified in constructor this.$container = $( this.getClosestScrollableElementContainer() ); } // Set height and width before measuring things, since it might cause our measurements // to change (e.g. due to scrollbars appearing or disappearing) this.$popup.css( { width: this.width, height: this.height !== null ? this.height : 'auto' } ); // Compute initial popupOffset based on alignment popupOffset = this.width * ( { left: 0, center: -0.5, right: -1 } )[ this.align ]; // Figure out if this will cause the popup to go beyond the edge of the container originOffset = this.$element.offset().left; containerLeft = this.$container.offset().left; containerWidth = this.$container.innerWidth(); containerRight = containerLeft + containerWidth; popupLeft = popupOffset - this.containerPadding; popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding; overlapLeft = ( originOffset + popupLeft ) - containerLeft; overlapRight = containerRight - ( originOffset + popupRight ); // Adjust offset to make the popup not go beyond the edge, if needed if ( overlapRight < 0 ) { popupOffset += overlapRight; } else if ( overlapLeft < 0 ) { popupOffset -= overlapLeft; } // Adjust offset to avoid anchor being rendered too close to the edge // $anchor.width() doesn't work with the pure CSS anchor (returns 0) // TODO: Find a measurement that works for CSS anchors and image anchors anchorWidth = this.$anchor[ 0 ].scrollWidth * 2; if ( popupOffset + this.width < anchorWidth ) { popupOffset = anchorWidth - this.width; } else if ( -popupOffset < anchorWidth ) { popupOffset = -anchorWidth; } // Prevent transition from being interrupted clearTimeout( this.transitionTimeout ); if ( transition ) { // Enable transition this.$element.addClass( 'oo-ui-popupWidget-transitioning' ); } // Position body relative to anchor this.$popup.css( 'margin-left', popupOffset ); if ( transition ) { // Prevent transitioning after transition is complete this.transitionTimeout = setTimeout( function () { widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' ); }, 200 ); } else { // Prevent transitioning immediately this.$element.removeClass( 'oo-ui-popupWidget-transitioning' ); } // Reevaluate clipping state since we've relocated and resized the popup this.clip(); return this; }; /** * Progress bars visually display the status of an operation, such as a download, * and can be either determinate or indeterminate: * * - **determinate** process bars show the percent of an operation that is complete. * * - **indeterminate** process bars use a visual display of motion to indicate that an operation * is taking place. Because the extent of an indeterminate operation is unknown, the bar does * not use percentages. * * The value of the `progress` configuration determines whether the bar is determinate or indeterminate. * * @example * // Examples of determinate and indeterminate progress bars. * var progressBar1 = new OO.ui.ProgressBarWidget( { * progress: 33 * } ); * var progressBar2 = new OO.ui.ProgressBarWidget(); * * // Create a FieldsetLayout to layout progress bars * var fieldset = new OO.ui.FieldsetLayout; * fieldset.addItems( [ * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}), * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'}) * ] ); * $( 'body' ).append( fieldset.$element ); * * @class * @extends OO.ui.Widget * * @constructor * @param {Object} [config] Configuration options * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate). * To create a determinate progress bar, specify a number that reflects the initial percent complete. * By default, the progress bar is indeterminate. */ OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.ProgressBarWidget.super.call( this, config ); // Properties this.$bar = $( '<div>' ); this.progress = null; // Initialization this.setProgress( config.progress !== undefined ? config.progress : false ); this.$bar.addClass( 'oo-ui-progressBarWidget-bar' ); this.$element .attr( { role: 'progressbar', 'aria-valuemin': 0, 'aria-valuemax': 100 } ) .addClass( 'oo-ui-progressBarWidget' ) .append( this.$bar ); }; /* Setup */ OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget ); /* Static Properties */ OO.ui.ProgressBarWidget.static.tagName = 'div'; /* Methods */ /** * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`. * * @return {number|boolean} Progress percent */ OO.ui.ProgressBarWidget.prototype.getProgress = function () { return this.progress; }; /** * Set the percent of the process completed or `false` for an indeterminate process. * * @param {number|boolean} progress Progress percent or `false` for indeterminate */ OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) { this.progress = progress; if ( progress !== false ) { this.$bar.css( 'width', this.progress + '%' ); this.$element.attr( 'aria-valuenow', this.progress ); } else { this.$bar.css( 'width', '' ); this.$element.removeAttr( 'aria-valuenow' ); } this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress ); }; /** * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query, * and a {@link OO.ui.TextInputMenuSelectWidget menu} of search results, which is displayed beneath the query * field. Unlike {@link OO.ui.LookupElement lookup menus}, search result menus are always visible to the user. * Users can choose an item from the menu or type a query into the text field to search for a matching result item. * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window. * * Each time the query is changed, the search result menu is cleared and repopulated. Please see * the [OOjs UI demos][1] for an example. * * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr * * @class * @extends OO.ui.Widget * * @constructor * @param {Object} [config] Configuration options * @cfg {string|jQuery} [placeholder] Placeholder text for query input * @cfg {string} [value] Initial query value */ OO.ui.SearchWidget = function OoUiSearchWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.SearchWidget.super.call( this, config ); // Properties this.query = new OO.ui.TextInputWidget( { icon: 'search', placeholder: config.placeholder, value: config.value } ); this.results = new OO.ui.SelectWidget(); this.$query = $( '<div>' ); this.$results = $( '<div>' ); // Events this.query.connect( this, { change: 'onQueryChange', enter: 'onQueryEnter' } ); this.results.connect( this, { highlight: 'onResultsHighlight', select: 'onResultsSelect' } ); this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) ); // Initialization this.$query .addClass( 'oo-ui-searchWidget-query' ) .append( this.query.$element ); this.$results .addClass( 'oo-ui-searchWidget-results' ) .append( this.results.$element ); this.$element .addClass( 'oo-ui-searchWidget' ) .append( this.$results, this.$query ); }; /* Setup */ OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget ); /* Events */ /** * A 'highlight' event is emitted when an item is highlighted. The highlight indicates which * item will be selected. When a user mouses over a menu item, it is highlighted. If a search * string is typed into the query field instead, the first menu item that matches the query * will be highlighted. * @event highlight * @param {Object|null} item Item data or null if no item is highlighted */ /** * A 'select' event is emitted when an item is selected. A menu item is selected when it is clicked, * or when a user types a search query, a menu result is highlighted, and the user presses enter. * * @event select * @param {Object|null} item Item data or null if no item is selected */ /* Methods */ /** * Handle query key down events. * * @private * @param {jQuery.Event} e Key down event */ OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) { var highlightedItem, nextItem, dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 ); if ( dir ) { highlightedItem = this.results.getHighlightedItem(); if ( !highlightedItem ) { highlightedItem = this.results.getSelectedItem(); } nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir ); this.results.highlightItem( nextItem ); nextItem.scrollElementIntoView(); } }; /** * Handle select widget select events. * * Clears existing results. Subclasses should repopulate items according to new query. * * @private * @param {string} value New value */ OO.ui.SearchWidget.prototype.onQueryChange = function () { // Reset this.results.clearItems(); }; /** * Handle select widget enter key events. * * Selects highlighted item. * * @private * @param {string} value New value */ OO.ui.SearchWidget.prototype.onQueryEnter = function () { // Reset this.results.selectItem( this.results.getHighlightedItem() ); }; /** * Handle select widget highlight events. * * @private * @param {OO.ui.OptionWidget} item Highlighted item * @fires highlight */ OO.ui.SearchWidget.prototype.onResultsHighlight = function ( item ) { this.emit( 'highlight', item ? item.getData() : null ); }; /** * Handle select widget select events. * * @private * @param {OO.ui.OptionWidget} item Selected item * @fires select */ OO.ui.SearchWidget.prototype.onResultsSelect = function ( item ) { this.emit( 'select', item ? item.getData() : null ); }; /** * Get the query input. * * @return {OO.ui.TextInputWidget} Query input */ OO.ui.SearchWidget.prototype.getQuery = function () { return this.query; }; /** * Get the search results menu. * * @return {OO.ui.SelectWidget} Menu of search results */ OO.ui.SearchWidget.prototype.getResults = function () { return this.results; }; /** * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of * select widgets, including {@link OO.ui.ButtonSelectWidget button selects}, * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget * menu selects}. * * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more * information, please see the [OOjs UI documentation on MediaWiki][1]. * * @example * // Example of a select widget with three options * var select = new OO.ui.SelectWidget( { * items: [ * new OO.ui.OptionWidget( { * data: 'a', * label: 'Option One', * } ), * new OO.ui.OptionWidget( { * data: 'b', * label: 'Option Two', * } ), * new OO.ui.OptionWidget( { * data: 'c', * label: 'Option Three', * } ) * ] * } ); * $( 'body' ).append( select.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options * * @class * @extends OO.ui.Widget * @mixins OO.ui.GroupElement * * @constructor * @param {Object} [config] Configuration options * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select. * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See * the [OOjs UI documentation on MediaWiki] [2] for examples. * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options */ OO.ui.SelectWidget = function OoUiSelectWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.SelectWidget.super.call( this, config ); // Mixin constructors OO.ui.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) ); // Properties this.pressed = false; this.selecting = null; this.onMouseUpHandler = this.onMouseUp.bind( this ); this.onMouseMoveHandler = this.onMouseMove.bind( this ); this.onKeyDownHandler = this.onKeyDown.bind( this ); // Events this.$element.on( { mousedown: this.onMouseDown.bind( this ), mouseover: this.onMouseOver.bind( this ), mouseleave: this.onMouseLeave.bind( this ) } ); // Initialization this.$element .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' ) .attr( 'role', 'listbox' ); if ( Array.isArray( config.items ) ) { this.addItems( config.items ); } }; /* Setup */ OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget ); // Need to mixin base class as well OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupElement ); OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupWidget ); /* Events */ /** * @event highlight * * A `highlight` event is emitted when the highlight is changed with the #highlightItem method. * * @param {OO.ui.OptionWidget|null} item Highlighted item */ /** * @event press * * A `press` event is emitted when the #pressItem method is used to programmatically modify the * pressed state of an option. * * @param {OO.ui.OptionWidget|null} item Pressed item */ /** * @event select * * A `select` event is emitted when the selection is modified programmatically with the #selectItem method. * * @param {OO.ui.OptionWidget|null} item Selected item */ /** * @event choose * A `choose` event is emitted when an item is chosen with the #chooseItem method. * @param {OO.ui.OptionWidget|null} item Chosen item */ /** * @event add * * An `add` event is emitted when options are added to the select with the #addItems method. * * @param {OO.ui.OptionWidget[]} items Added items * @param {number} index Index of insertion point */ /** * @event remove * * A `remove` event is emitted when options are removed from the select with the #clearItems * or #removeItems methods. * * @param {OO.ui.OptionWidget[]} items Removed items */ /* Methods */ /** * Handle mouse down events. * * @private * @param {jQuery.Event} e Mouse down event */ OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) { var item; if ( !this.isDisabled() && e.which === 1 ) { this.togglePressed( true ); item = this.getTargetItem( e ); if ( item && item.isSelectable() ) { this.pressItem( item ); this.selecting = item; this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true ); this.getElementDocument().addEventListener( 'mousemove', this.onMouseMoveHandler, true ); } } return false; }; /** * Handle mouse up events. * * @private * @param {jQuery.Event} e Mouse up event */ OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) { var item; this.togglePressed( false ); if ( !this.selecting ) { item = this.getTargetItem( e ); if ( item && item.isSelectable() ) { this.selecting = item; } } if ( !this.isDisabled() && e.which === 1 && this.selecting ) { this.pressItem( null ); this.chooseItem( this.selecting ); this.selecting = null; } this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true ); this.getElementDocument().removeEventListener( 'mousemove', this.onMouseMoveHandler, true ); return false; }; /** * Handle mouse move events. * * @private * @param {jQuery.Event} e Mouse move event */ OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) { var item; if ( !this.isDisabled() && this.pressed ) { item = this.getTargetItem( e ); if ( item && item !== this.selecting && item.isSelectable() ) { this.pressItem( item ); this.selecting = item; } } return false; }; /** * Handle mouse over events. * * @private * @param {jQuery.Event} e Mouse over event */ OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) { var item; if ( !this.isDisabled() ) { item = this.getTargetItem( e ); this.highlightItem( item && item.isHighlightable() ? item : null ); } return false; }; /** * Handle mouse leave events. * * @private * @param {jQuery.Event} e Mouse over event */ OO.ui.SelectWidget.prototype.onMouseLeave = function () { if ( !this.isDisabled() ) { this.highlightItem( null ); } return false; }; /** * Handle key down events. * * @protected * @param {jQuery.Event} e Key down event */ OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) { var nextItem, handled = false, currentItem = this.getHighlightedItem() || this.getSelectedItem(); if ( !this.isDisabled() && this.isVisible() ) { switch ( e.keyCode ) { case OO.ui.Keys.ENTER: if ( currentItem && currentItem.constructor.static.highlightable ) { // Was only highlighted, now let's select it. No-op if already selected. this.chooseItem( currentItem ); handled = true; } break; case OO.ui.Keys.UP: case OO.ui.Keys.LEFT: nextItem = this.getRelativeSelectableItem( currentItem, -1 ); handled = true; break; case OO.ui.Keys.DOWN: case OO.ui.Keys.RIGHT: nextItem = this.getRelativeSelectableItem( currentItem, 1 ); handled = true; break; case OO.ui.Keys.ESCAPE: case OO.ui.Keys.TAB: if ( currentItem && currentItem.constructor.static.highlightable ) { currentItem.setHighlighted( false ); } this.unbindKeyDownListener(); // Don't prevent tabbing away / defocusing handled = false; break; } if ( nextItem ) { if ( nextItem.constructor.static.highlightable ) { this.highlightItem( nextItem ); } else { this.chooseItem( nextItem ); } nextItem.scrollElementIntoView(); } if ( handled ) { // Can't just return false, because e is not always a jQuery event e.preventDefault(); e.stopPropagation(); } } }; /** * Bind key down listener. * * @protected */ OO.ui.SelectWidget.prototype.bindKeyDownListener = function () { this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler, true ); }; /** * Unbind key down listener. * * @protected */ OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () { this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler, true ); }; /** * Get the closest item to a jQuery.Event. * * @private * @param {jQuery.Event} e * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found */ OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) { var $item = $( e.target ).closest( '.oo-ui-optionWidget' ); if ( $item.length ) { return $item.data( 'oo-ui-optionWidget' ); } return null; }; /** * Get selected item. * * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected */ OO.ui.SelectWidget.prototype.getSelectedItem = function () { var i, len; for ( i = 0, len = this.items.length; i < len; i++ ) { if ( this.items[ i ].isSelected() ) { return this.items[ i ]; } } return null; }; /** * Get highlighted item. * * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted */ OO.ui.SelectWidget.prototype.getHighlightedItem = function () { var i, len; for ( i = 0, len = this.items.length; i < len; i++ ) { if ( this.items[ i ].isHighlighted() ) { return this.items[ i ]; } } return null; }; /** * Toggle pressed state. * * Press is a state that occurs when a user mouses down on an item, but * has not yet let go of the mouse. The item may appear selected, but it will not be selected * until the user releases the mouse. * * @param {boolean} pressed An option is being pressed */ OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) { if ( pressed === undefined ) { pressed = !this.pressed; } if ( pressed !== this.pressed ) { this.$element .toggleClass( 'oo-ui-selectWidget-pressed', pressed ) .toggleClass( 'oo-ui-selectWidget-depressed', !pressed ); this.pressed = pressed; } }; /** * Highlight an option. If the `item` param is omitted, no options will be highlighted * and any existing highlight will be removed. The highlight is mutually exclusive. * * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight * @fires highlight * @chainable */ OO.ui.SelectWidget.prototype.highlightItem = function ( item ) { var i, len, highlighted, changed = false; for ( i = 0, len = this.items.length; i < len; i++ ) { highlighted = this.items[ i ] === item; if ( this.items[ i ].isHighlighted() !== highlighted ) { this.items[ i ].setHighlighted( highlighted ); changed = true; } } if ( changed ) { this.emit( 'highlight', item ); } return this; }; /** * Programmatically select an option by its reference. If the `item` parameter is omitted, * all options will be deselected. * * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all * @fires select * @chainable */ OO.ui.SelectWidget.prototype.selectItem = function ( item ) { var i, len, selected, changed = false; for ( i = 0, len = this.items.length; i < len; i++ ) { selected = this.items[ i ] === item; if ( this.items[ i ].isSelected() !== selected ) { this.items[ i ].setSelected( selected ); changed = true; } } if ( changed ) { this.emit( 'select', item ); } return this; }; /** * Press an item. * * Press is a state that occurs when a user mouses down on an item, but has not * yet let go of the mouse. The item may appear selected, but it will not be selected until the user * releases the mouse. * * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all * @fires press * @chainable */ OO.ui.SelectWidget.prototype.pressItem = function ( item ) { var i, len, pressed, changed = false; for ( i = 0, len = this.items.length; i < len; i++ ) { pressed = this.items[ i ] === item; if ( this.items[ i ].isPressed() !== pressed ) { this.items[ i ].setPressed( pressed ); changed = true; } } if ( changed ) { this.emit( 'press', item ); } return this; }; /** * Choose an item. * * Note that ‘choose’ should never be modified programmatically. A user can choose * an option with the keyboard or mouse and it becomes selected. To select an item programmatically, * use the #selectItem method. * * This method is identical to #selectItem, but may vary in subclasses that take additional action * when users choose an item with the keyboard or mouse. * * @param {OO.ui.OptionWidget} item Item to choose * @fires choose * @chainable */ OO.ui.SelectWidget.prototype.chooseItem = function ( item ) { this.selectItem( item ); this.emit( 'choose', item ); return this; }; /** * Get an option by its position relative to the specified item (or to the start of the option array, * if item is `null`). The direction in which to search through the option array is specified with a * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or * `null` if there are no options in the array. * * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array. * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select */ OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction ) { var currentIndex, nextIndex, i, increase = direction > 0 ? 1 : -1, len = this.items.length; if ( item instanceof OO.ui.OptionWidget ) { currentIndex = $.inArray( item, this.items ); nextIndex = ( currentIndex + increase + len ) % len; } else { // If no item is selected and moving forward, start at the beginning. // If moving backward, start at the end. nextIndex = direction > 0 ? 0 : len - 1; } for ( i = 0; i < len; i++ ) { item = this.items[ nextIndex ]; if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) { return item; } nextIndex = ( nextIndex + increase + len ) % len; } return null; }; /** * Get the next selectable item or `null` if there are no selectable items. * Disabled options and menu-section markers and breaks are not selectable. * * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items */ OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () { var i, len, item; for ( i = 0, len = this.items.length; i < len; i++ ) { item = this.items[ i ]; if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) { return item; } } return null; }; /** * Add an array of options to the select. Optionally, an index number can be used to * specify an insertion point. * * @param {OO.ui.OptionWidget[]} items Items to add * @param {number} [index] Index to insert items after * @fires add * @chainable */ OO.ui.SelectWidget.prototype.addItems = function ( items, index ) { // Mixin method OO.ui.GroupWidget.prototype.addItems.call( this, items, index ); // Always provide an index, even if it was omitted this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index ); return this; }; /** * Remove the specified array of options from the select. Options will be detached * from the DOM, not removed, so they can be reused later. To remove all options from * the select, you may wish to use the #clearItems method instead. * * @param {OO.ui.OptionWidget[]} items Items to remove * @fires remove * @chainable */ OO.ui.SelectWidget.prototype.removeItems = function ( items ) { var i, len, item; // Deselect items being removed for ( i = 0, len = items.length; i < len; i++ ) { item = items[ i ]; if ( item.isSelected() ) { this.selectItem( null ); } } // Mixin method OO.ui.GroupWidget.prototype.removeItems.call( this, items ); this.emit( 'remove', items ); return this; }; /** * Clear all options from the select. Options will be detached from the DOM, not removed, * so that they can be reused later. To remove a subset of options from the select, use * the #removeItems method. * * @fires remove * @chainable */ OO.ui.SelectWidget.prototype.clearItems = function () { var items = this.items.slice(); // Mixin method OO.ui.GroupWidget.prototype.clearItems.call( this ); // Clear selection this.selectItem( null ); this.emit( 'remove', items ); return this; }; /** * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains * button options and is used together with * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for * highlighting, choosing, and selecting mutually exclusive options. Please see * the [OOjs UI documentation on MediaWiki] [1] for more information. * * @example * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets * var option1 = new OO.ui.ButtonOptionWidget( { * data: 1, * label: 'Option 1', * title: 'Button option 1' * } ); * * var option2 = new OO.ui.ButtonOptionWidget( { * data: 2, * label: 'Option 2', * title: 'Button option 2' * } ); * * var option3 = new OO.ui.ButtonOptionWidget( { * data: 3, * label: 'Option 3', * title: 'Button option 3' * } ); * * var buttonSelect=new OO.ui.ButtonSelectWidget( { * items: [ option1, option2, option3 ] * } ); * $( 'body' ).append( buttonSelect.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options * * @class * @extends OO.ui.SelectWidget * @mixins OO.ui.TabIndexedElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) { // Parent constructor OO.ui.ButtonSelectWidget.super.call( this, config ); // Mixin constructors OO.ui.TabIndexedElement.call( this, config ); // Events this.$element.on( { focus: this.bindKeyDownListener.bind( this ), blur: this.unbindKeyDownListener.bind( this ) } ); // Initialization this.$element.addClass( 'oo-ui-buttonSelectWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget ); OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.TabIndexedElement ); /** * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides * an interface for adding, removing and selecting options. * Please see the [OOjs UI documentation on MediaWiki][1] for more information. * * @example * // A RadioSelectWidget with RadioOptions. * var option1 = new OO.ui.RadioOptionWidget( { * data: 'a', * label: 'Selected radio option' * } ); * * var option2 = new OO.ui.RadioOptionWidget( { * data: 'b', * label: 'Unselected radio option' * } ); * * var radioSelect=new OO.ui.RadioSelectWidget( { * items: [ option1, option2 ] * } ); * * // Select 'option 1' using the RadioSelectWidget's selectItem() method. * radioSelect.selectItem( option1 ); * * $( 'body' ).append( radioSelect.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options * * @class * @extends OO.ui.SelectWidget * @mixins OO.ui.TabIndexedElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) { // Parent constructor OO.ui.RadioSelectWidget.super.call( this, config ); // Mixin constructors OO.ui.TabIndexedElement.call( this, config ); // Events this.$element.on( { focus: this.bindKeyDownListener.bind( this ), blur: this.unbindKeyDownListener.bind( this ) } ); // Initialization this.$element.addClass( 'oo-ui-radioSelectWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget ); OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.TabIndexedElement ); /** * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget. * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget}, * and {@link OO.ui.LookupElement LookupElement} for examples of widgets that contain menus. * MenuSelectWidgets themselves are not instantiated directly, rather subclassed * and customized to be opened, closed, and displayed as needed. * * By default, menus are clipped to the visible viewport and are not visible when a user presses the * mouse outside the menu. * * Menus also have support for keyboard interaction: * * - Enter/Return key: choose and select a menu option * - Up-arrow key: highlight the previous menu option * - Down-arrow key: highlight the next menu option * - Esc key: hide the menu * * Please see the [OOjs UI documentation on MediaWiki][1] for more information. * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options * * @class * @extends OO.ui.SelectWidget * @mixins OO.ui.ClippableElement * * @constructor * @param {Object} [config] Configuration options * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget} * and {@link OO.ui.LookupElement LookupElement} * @cfg {OO.ui.Widget} [widget] Widget associated with the menu’s active state. If the user clicks the mouse * anywhere on the page outside of this widget, the menu is hidden. * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu. */ OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.MenuSelectWidget.super.call( this, config ); // Mixin constructors OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) ); // Properties this.newItems = null; this.autoHide = config.autoHide === undefined || !!config.autoHide; this.$input = config.input ? config.input.$input : null; this.$widget = config.widget ? config.widget.$element : null; this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this ); // Initialization this.$element .addClass( 'oo-ui-menuSelectWidget' ) .attr( 'role', 'menu' ); // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods // that reference properties not initialized at that time of parent class construction // TODO: Find a better way to handle post-constructor setup this.visible = false; this.$element.addClass( 'oo-ui-element-hidden' ); }; /* Setup */ OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget ); OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.ClippableElement ); /* Methods */ /** * Handles document mouse down events. * * @protected * @param {jQuery.Event} e Key down event */ OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) { if ( !OO.ui.contains( this.$element[ 0 ], e.target, true ) && ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) ) ) { this.toggle( false ); } }; /** * @inheritdoc */ OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) { var currentItem = this.getHighlightedItem() || this.getSelectedItem(); if ( !this.isDisabled() && this.isVisible() ) { switch ( e.keyCode ) { case OO.ui.Keys.LEFT: case OO.ui.Keys.RIGHT: // Do nothing if a text field is associated, arrow keys will be handled natively if ( !this.$input ) { OO.ui.MenuSelectWidget.super.prototype.onKeyDown.call( this, e ); } break; case OO.ui.Keys.ESCAPE: case OO.ui.Keys.TAB: if ( currentItem ) { currentItem.setHighlighted( false ); } this.toggle( false ); // Don't prevent tabbing away, prevent defocusing if ( e.keyCode === OO.ui.Keys.ESCAPE ) { e.preventDefault(); e.stopPropagation(); } break; default: OO.ui.MenuSelectWidget.super.prototype.onKeyDown.call( this, e ); return; } } }; /** * @inheritdoc */ OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () { if ( this.$input ) { this.$input.on( 'keydown', this.onKeyDownHandler ); } else { OO.ui.MenuSelectWidget.super.prototype.bindKeyDownListener.call( this ); } }; /** * @inheritdoc */ OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () { if ( this.$input ) { this.$input.off( 'keydown', this.onKeyDownHandler ); } else { OO.ui.MenuSelectWidget.super.prototype.unbindKeyDownListener.call( this ); } }; /** * Choose an item. * * When a user chooses an item, the menu is closed. * * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method. * @param {OO.ui.OptionWidget} item Item to choose * @chainable */ OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) { OO.ui.MenuSelectWidget.super.prototype.chooseItem.call( this, item ); this.toggle( false ); return this; }; /** * @inheritdoc */ OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) { var i, len, item; // Parent method OO.ui.MenuSelectWidget.super.prototype.addItems.call( this, items, index ); // Auto-initialize if ( !this.newItems ) { this.newItems = []; } for ( i = 0, len = items.length; i < len; i++ ) { item = items[ i ]; if ( this.isVisible() ) { // Defer fitting label until item has been attached item.fitLabel(); } else { this.newItems.push( item ); } } // Reevaluate clipping this.clip(); return this; }; /** * @inheritdoc */ OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) { // Parent method OO.ui.MenuSelectWidget.super.prototype.removeItems.call( this, items ); // Reevaluate clipping this.clip(); return this; }; /** * @inheritdoc */ OO.ui.MenuSelectWidget.prototype.clearItems = function () { // Parent method OO.ui.MenuSelectWidget.super.prototype.clearItems.call( this ); // Reevaluate clipping this.clip(); return this; }; /** * @inheritdoc */ OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) { visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length; var i, len, change = visible !== this.isVisible(); // Parent method OO.ui.MenuSelectWidget.super.prototype.toggle.call( this, visible ); if ( change ) { if ( visible ) { this.bindKeyDownListener(); if ( this.newItems && this.newItems.length ) { for ( i = 0, len = this.newItems.length; i < len; i++ ) { this.newItems[ i ].fitLabel(); } this.newItems = null; } this.toggleClipping( true ); // Auto-hide if ( this.autoHide ) { this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler, true ); } } else { this.unbindKeyDownListener(); this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler, true ); this.toggleClipping( false ); } } return this; }; /** * TextInputMenuSelectWidget is a menu that is specially designed to be positioned beneath * a {@link OO.ui.TextInputWidget text input} field. The menu's position is automatically * calculated and maintained when the menu is toggled or the window is resized. * See OO.ui.ComboBoxWidget for an example of a widget that uses this class. * * @class * @extends OO.ui.MenuSelectWidget * * @constructor * @param {OO.ui.TextInputWidget} inputWidget Text input widget to provide menu for * @param {Object} [config] Configuration options * @cfg {jQuery} [$container=input.$element] Element to render menu under */ OO.ui.TextInputMenuSelectWidget = function OoUiTextInputMenuSelectWidget( inputWidget, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( inputWidget ) && config === undefined ) { config = inputWidget; inputWidget = config.inputWidget; } // Configuration initialization config = config || {}; // Parent constructor OO.ui.TextInputMenuSelectWidget.super.call( this, config ); // Properties this.inputWidget = inputWidget; this.$container = config.$container || this.inputWidget.$element; this.onWindowResizeHandler = this.onWindowResize.bind( this ); // Initialization this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.TextInputMenuSelectWidget, OO.ui.MenuSelectWidget ); /* Methods */ /** * Handle window resize event. * * @private * @param {jQuery.Event} e Window resize event */ OO.ui.TextInputMenuSelectWidget.prototype.onWindowResize = function () { this.position(); }; /** * @inheritdoc */ OO.ui.TextInputMenuSelectWidget.prototype.toggle = function ( visible ) { visible = visible === undefined ? !this.isVisible() : !!visible; var change = visible !== this.isVisible(); if ( change && visible ) { // Make sure the width is set before the parent method runs. // After this we have to call this.position(); again to actually // position ourselves correctly. this.position(); } // Parent method OO.ui.TextInputMenuSelectWidget.super.prototype.toggle.call( this, visible ); if ( change ) { if ( this.isVisible() ) { this.position(); $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler ); } else { $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler ); } } return this; }; /** * Position the menu. * * @private * @chainable */ OO.ui.TextInputMenuSelectWidget.prototype.position = function () { var $container = this.$container, pos = OO.ui.Element.static.getRelativePosition( $container, this.$element.offsetParent() ); // Position under input pos.top += $container.height(); this.$element.css( pos ); // Set width this.setIdealSize( $container.width() ); // We updated the position, so re-evaluate the clipping state this.clip(); return this; }; /** * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options} * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget. * * ####Currently, this class is only used by {@link OO.ui.BookletLayout BookletLayouts}.#### * * @class * @extends OO.ui.SelectWidget * @mixins OO.ui.TabIndexedElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) { // Parent constructor OO.ui.OutlineSelectWidget.super.call( this, config ); // Mixin constructors OO.ui.TabIndexedElement.call( this, config ); // Events this.$element.on( { focus: this.bindKeyDownListener.bind( this ), blur: this.unbindKeyDownListener.bind( this ) } ); // Initialization this.$element.addClass( 'oo-ui-outlineSelectWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget ); OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.TabIndexedElement ); /** * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented * visually by a slider in the leftmost position. * * @example * // Toggle switches in the 'off' and 'on' position. * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget(); * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( { * value: true * } ); * * // Create a FieldsetLayout to layout and label switches * var fieldset = new OO.ui.FieldsetLayout( { * label: 'Toggle switches' * } ); * fieldset.addItems( [ * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ), * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } ) * ] ); * $( 'body' ).append( fieldset.$element ); * * @class * @extends OO.ui.Widget * @mixins OO.ui.ToggleWidget * @mixins OO.ui.TabIndexedElement * * @constructor * @param {Object} [config] Configuration options * @cfg {boolean} [value=false] The toggle switch’s initial on/off state. * By default, the toggle switch is in the 'off' position. */ OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) { // Parent constructor OO.ui.ToggleSwitchWidget.super.call( this, config ); // Mixin constructors OO.ui.ToggleWidget.call( this, config ); OO.ui.TabIndexedElement.call( this, config ); // Properties this.dragging = false; this.dragStart = null; this.sliding = false; this.$glow = $( '<span>' ); this.$grip = $( '<span>' ); // Events this.$element.on( { click: this.onClick.bind( this ), keypress: this.onKeyPress.bind( this ) } ); // Initialization this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' ); this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' ); this.$element .addClass( 'oo-ui-toggleSwitchWidget' ) .attr( 'role', 'checkbox' ) .append( this.$glow, this.$grip ); }; /* Setup */ OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget ); OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.TabIndexedElement ); /* Methods */ /** * Handle mouse click events. * * @private * @param {jQuery.Event} e Mouse click event */ OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) { if ( !this.isDisabled() && e.which === 1 ) { this.setValue( !this.value ); } return false; }; /** * Handle key press events. * * @private * @param {jQuery.Event} e Key press event */ OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) { if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) { this.setValue( !this.value ); return false; } }; }( OO ) );
examples/src/Example.js
perminder-klair/react-sound
import React from 'react'; import Sound from 'react-sound'; import PlayerControls from './PlayerControls'; import SongSelector from './SongSelector'; import songs from './songs'; export default class Example extends React.Component { constructor(props) { super(props); this.state = { currentSong: songs[0], position: 0, playStatus: Sound.status.PLAYING }; } render() { return <div> <SongSelector songs={songs} selectedSong={this.state.currentSong} onSongSelected={this.handleSongSelected.bind(this)} /> {this.state.currentSong && this.renderCurrentSong()} <PlayerControls playStatus={this.state.playStatus} onPlay={() => this.setState({playStatus: Sound.status.PLAYING})} onPause={() => this.setState({playStatus: Sound.status.PAUSED})} onResume={() => this.setState({playStatus: Sound.status.PLAYING})} onStop={() => this.setState({playStatus: Sound.status.STOPPED, position: 0})} onSeek={position => this.setState({ position })} duration={this.state.currentSong ? this.state.currentSong.duration : 0} position={this.state.position} /> {this.state.currentSong && <Sound url={this.state.currentSong.url} playStatus={this.state.playStatus} playFromPosition={this.state.position} onLoading={({bytesLoaded, bytesTotal}) => console.log(`${bytesLoaded / bytesTotal * 100}% loaded`)} onPlaying={({position}) => console.log(position)} onFinishedPlaying={() => this.setState({playStatus: Sound.status.STOPPED})} />} </div>; } renderCurrentSong() { return <p> Currently playing {this.state.currentSong.title} </p>; } handleSongSelected(song) { this.setState({currentSong: song, position: 0, playStatus: Sound.status.STOPPED}); } }
core/src/main/webapp/static/js/jquery-1.11.1.js
rincexwind/Heimdal
/*! * jQuery JavaScript Library v1.11.1 * 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-05-01T17:42Z */ (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 support = {}; var version = "1.11.1", // 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 ); }, // Support: Android<4.1, IE<9 // Make sure we trim BOM and NBSP 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 just the one element from the set ( num < 0 ? this[ num + this.length ] : this[ num ] ) : // Return all the elements in a clean array 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 !jQuery.isArray( obj ) && 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; }, // Support: Android<4.1, IE<9 trim: 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.19 * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-04-18 */ (function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, 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#" ), // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + characterEncoding + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // 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<24 // 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 msallowclip=''><option selected=''></option></select>"; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( div.querySelectorAll("[msallowclip^='']").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.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[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[6] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] ) { match[2] = match[4] || match[5] || ""; // 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(); tokenize = Sizzle.tokenize = function( 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 multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } 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, match /* 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 ( !match ) { match = tokenize( selector ); } i = match.length; while ( i-- ) { cached = matcherFromTokens( match[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; }; /** * A low-level selection function that works with Sizzle's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled * selector function built with Sizzle.compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( (selector = compiled.selector || selector) ); results = results || []; // Try to minimize operations if there is no seed and 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; // Precompiled matchers will still verify ancestry, so step up a level } else if ( compiled ) { context = context.parentNode; } 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 if one is not provided // Provide `match` to avoid retokenization if we modified the selector above ( compiled || 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.triggerHandler ) { jQuery( document ).triggerHandler( "ready" ); jQuery( document ).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; // Execute ASAP in case we need to set body.style.zoom jQuery(function() { // Minified: var a,b,c,d var val, div, body, container; body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body || !body.style ) { // Return for frameset docs that don't have a body return; } // Setup div = document.createElement( "div" ); container = document.createElement( "div" ); container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; 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 = "display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1"; support.inlineBlockNeedsLayout = val = div.offsetWidth === 3; if ( val ) { // 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 ); }); (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-- ) { // Support: IE11+ // The attrs elements can be null (#14894) if ( attrs[ 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() { // Minified: var a,b,c var input = document.createElement( "input" ), div = document.createElement( "div" ), fragment = document.createDocumentFragment(); // Setup div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // 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; } } })(); (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|pointer|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 ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined && event.originalEvent ) { 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, Android < 4.0 src.returnValue === false ? 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() { var e = this.originalEvent; this.isImmediatePropagationStopped = returnTrue; if ( e && e.stopImmediatePropagation ) { e.stopImmediatePropagation(); } this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, 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 style, elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), // getDefaultComputedStyle might be reliably used only on attached element display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ? // 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 style.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 shrinkWrapBlocksVal; support.shrinkWrapBlocks = function() { if ( shrinkWrapBlocksVal != null ) { return shrinkWrapBlocksVal; } // Will be changed later if needed. shrinkWrapBlocksVal = false; // Minified: var b,c,d var div, body, container; body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body || !body.style ) { // Test fired too early or in an unsupported environment, exit. return; } // Setup div = document.createElement( "div" ); container = document.createElement( "div" ); container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; body.appendChild( container ).appendChild( div ); // Support: IE6 // Check if elements with layout shrink-wrap their children if ( typeof div.style.zoom !== strundefined ) { // Reset CSS: box-sizing; display; margin; border div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-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"; div.appendChild( document.createElement( "div" ) ).style.width = "5px"; shrinkWrapBlocksVal = div.offsetWidth !== 3; } body.removeChild( container ); 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() { // Minified: var b,c,d,e,f,g, h,i var div, style, a, pixelPositionVal, boxSizingReliableVal, reliableHiddenOffsetsVal, reliableMarginRightVal; // Setup div = document.createElement( "div" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; a = div.getElementsByTagName( "a" )[ 0 ]; style = a && a.style; // Finish early in limited (non-browser) environments if ( !style ) { return; } style.cssText = "float:left;opacity:.5"; // Support: IE<9 // Make sure that element opacity exists (as opposed to filter) support.opacity = style.opacity === "0.5"; // Verify style float existence // (IE uses styleFloat instead of cssFloat) support.cssFloat = !!style.cssFloat; div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing support.boxSizing = style.boxSizing === "" || style.MozBoxSizing === "" || style.WebkitBoxSizing === ""; jQuery.extend(support, { reliableHiddenOffsets: function() { if ( reliableHiddenOffsetsVal == null ) { computeStyleTests(); } return reliableHiddenOffsetsVal; }, boxSizingReliable: function() { if ( boxSizingReliableVal == null ) { computeStyleTests(); } return boxSizingReliableVal; }, pixelPosition: function() { if ( pixelPositionVal == null ) { computeStyleTests(); } return pixelPositionVal; }, // Support: Android 2.3 reliableMarginRight: function() { if ( reliableMarginRightVal == null ) { computeStyleTests(); } return reliableMarginRightVal; } }); function computeStyleTests() { // Minified: var b,c,d,j var div, body, container, contents; body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body || !body.style ) { // Test fired too early or in an unsupported environment, exit. return; } // Setup div = document.createElement( "div" ); container = document.createElement( "div" ); container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; body.appendChild( container ).appendChild( div ); div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-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"; // Support: IE<9 // Assume reasonable values in the absence of getComputedStyle pixelPositionVal = boxSizingReliableVal = false; reliableMarginRightVal = true; // Check for getComputedStyle so that this code is not run in IE<9. if ( window.getComputedStyle ) { pixelPositionVal = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; boxSizingReliableVal = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Support: Android 2.3 // Div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container (#3333) // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right contents = div.appendChild( document.createElement( "div" ) ); // Reset CSS: box-sizing; display; margin; border; padding contents.style.cssText = div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" + "box-sizing:content-box;display:block;margin:0;border:0;padding:0"; contents.style.marginRight = contents.style.width = "0"; div.style.width = "1px"; reliableMarginRightVal = !parseFloat( ( window.getComputedStyle( contents, null ) || {} ).marginRight ); } // 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>"; contents = div.getElementsByTagName( "td" ); contents[ 0 ].style.cssText = "margin:0;border:0;padding:0;display:none"; reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0; if ( reliableHiddenOffsetsVal ) { contents[ 0 ].style.display = ""; contents[ 1 ].style.display = "none"; reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0; } body.removeChild( container ); } })(); // 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 { 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, "flexGrow": true, "flexShrink": 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 { 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 rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ? 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, checkDisplay, 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" ); // Test default display if display is currently "none" checkDisplay = display === "none" ? jQuery._data( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display; if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !support.inlineBlockNeedsLayout || defaultDisplay( elem.nodeName ) === "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 ); // Any non-fx value stops us from restoring the original display value } else { display = undefined; } } 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; } } } // If this is a noop like .hide().hide(), restore an overwritten display value } else if ( (display === "none" ? defaultDisplay( elem.nodeName ) : display) === "inline" ) { style.display = display; } } 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() { // Minified: var a,b,c,d,e var input, div, select, a, opt; // Setup div = document.createElement( "div" ); 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"; })(); 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 : // Support: IE10-11+ // option.text throws exceptions (#14686, #14858) jQuery.trim( 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.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(); } }); 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 = jQuery.trim( 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; }; var docElem = window.document.documentElement; /** * Gets a window from an element */ function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } jQuery.offset = { setOffset: function( elem, options, i ) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery.css( elem, "position" ), curElem = jQuery( elem ), props = {}; // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } curOffset = curElem.offset(); curCSSTop = jQuery.css( elem, "top" ); curCSSLeft = jQuery.css( elem, "left" ); calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [ curCSSTop, curCSSLeft ] ) > -1; // 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({ 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 !== 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 ) }; }, 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 its 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 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 ); }; }); // Add the top/left cssHooks using jQuery.fn.position // 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 jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition, 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; } } ); }); // 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 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 ); }; }); }); // 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. // Note that for maximum portability, libraries that are not jQuery should // declare themselves as anonymous modules, and avoid setting a global if an // AMD loader is present. jQuery is a special case. For more information, see // https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon 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; }));
packages/material-ui-icons/src/PowerInputSharp.js
Kagami/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M2 9v2h19V9H2zm0 6h5v-2H2v2zm7 0h5v-2H9v2zm7 0h5v-2h-5v2z" /></g></React.Fragment> , 'PowerInputSharp');
app/src/scripts/widgets/Navigation/Navigation.js
vyorkin/assignment
import React from 'react'; import { Link } from 'react-router'; import './Navigation.css'; export default class Navigation { render() { return ( <nav className='navigation'> <ul> <li><Link to='index'>Индекс</Link></li> <li><Link to='playground'>Эксперименты</Link></li> </ul> </nav> ); } }
client/app/schema.js
DynamicTeapot/BitBargain
import React from 'react'; const item = React.PropTypes.shape({ title: React.PropTypes.string.isRequired, description: React.PropTypes.string.isRequired, price: React.PropTypes.string, location: React.PropTypes.string.isRequired, posted_at: React.PropTypes.string, updated_at: React.PropTypes.string, category: React.PropTypes.arrayOf(React.PropTypes.string).isRequired, images: React.PropTypes.arrayOf(React.PropTypes.string) }); export default item;
lib-module-node7/RedBoxWrapper.js
turacojs/fody
import React from 'react'; import RedBox from 'redbox-react'; export default (({ error }) => { if (error) { // eslint-disable-next-line no-console console.error(error.message || error, error.stack); } return React.createElement(RedBox, { error: error }); }); //# sourceMappingURL=RedBoxWrapper.js.map
files/xe-core/1.7.5.7/common/js/jquery-1.x.min.js
leebyron/jsdelivr
/*! jQuery v1.10.2 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license //@ sourceMappingURL=jquery-1.10.2.min.map */ (function(e,t){var n,r,i=typeof t,o=e.location,a=e.document,s=a.documentElement,l=e.jQuery,u=e.$,c={},p=[],f="1.10.2",d=p.concat,h=p.push,g=p.slice,m=p.indexOf,y=c.toString,v=c.hasOwnProperty,b=f.trim,x=function(e,t){return new x.fn.init(e,t,r)},w=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=/\S+/g,C=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,k=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,E=/^[\],:{}\s]*$/,S=/(?:^|:|,)(?:\s*\[)+/g,A=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,j=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,D=/^-ms-/,L=/-([\da-z])/gi,H=function(e,t){return t.toUpperCase()},q=function(e){(a.addEventListener||"load"===e.type||"complete"===a.readyState)&&(_(),x.ready())},_=function(){a.addEventListener?(a.removeEventListener("DOMContentLoaded",q,!1),e.removeEventListener("load",q,!1)):(a.detachEvent("onreadystatechange",q),e.detachEvent("onload",q))};x.fn=x.prototype={jquery:f,constructor:x,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]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof x?n[0]:n,x.merge(this,x.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:a,!0)),k.test(i[1])&&x.isPlainObject(n))for(i in n)x.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(o=a.getElementById(i[2]),o&&o.parentNode){if(o.id!==i[2])return r.find(e);this.length=1,this[0]=o}return this.context=a,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):x.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),x.makeArray(e,this))},selector:"",length:0,toArray:function(){return g.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=x.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return x.each(this,e,t)},ready:function(e){return x.ready.promise().done(e),this},slice:function(){return this.pushStack(g.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(x.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:h,sort:[].sort,splice:[].splice},x.fn.init.prototype=x.fn,x.extend=x.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},l=2),"object"==typeof s||x.isFunction(s)||(s={}),u===l&&(s=this,--l);u>l;l++)if(null!=(o=arguments[l]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(x.isPlainObject(r)||(n=x.isArray(r)))?(n?(n=!1,a=e&&x.isArray(e)?e:[]):a=e&&x.isPlainObject(e)?e:{},s[i]=x.extend(c,a,r)):r!==t&&(s[i]=r));return s},x.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),noConflict:function(t){return e.$===x&&(e.$=u),t&&e.jQuery===x&&(e.jQuery=l),x},isReady:!1,readyWait:1,holdReady:function(e){e?x.readyWait++:x.ready(!0)},ready:function(e){if(e===!0?!--x.readyWait:!x.isReady){if(!a.body)return setTimeout(x.ready);x.isReady=!0,e!==!0&&--x.readyWait>0||(n.resolveWith(a,[x]),x.fn.trigger&&x(a).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===x.type(e)},isArray:Array.isArray||function(e){return"array"===x.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?c[y.call(e)]||"object":typeof e},isPlainObject:function(e){var n;if(!e||"object"!==x.type(e)||e.nodeType||x.isWindow(e))return!1;try{if(e.constructor&&!v.call(e,"constructor")&&!v.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(r){return!1}if(x.support.ownLast)for(n in e)return v.call(e,n);for(n in e);return n===t||v.call(e,n)},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||a;var r=k.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=x.buildFragment([e],t,i),i&&x(i).remove(),x.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=x.trim(n),n&&E.test(n.replace(A,"@").replace(j,"]").replace(S,"")))?Function("return "+n)():(x.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||x.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&x.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(D,"ms-").replace(L,H)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:b&&!b.call("\ufeff\u00a0")?function(e){return null==e?"":b.call(e)}:function(e){return null==e?"":(e+"").replace(C,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?x.merge(n,"string"==typeof e?[e]:e):h.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(m)return m.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return d.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),x.isFunction(e)?(r=g.call(arguments,2),i=function(){return e.apply(n||this,r.concat(g.call(arguments)))},i.guid=e.guid=e.guid||x.guid++,i):t},access:function(e,n,r,i,o,a,s){var l=0,u=e.length,c=null==r;if("object"===x.type(r)){o=!0;for(l in r)x.access(e,n,l,r[l],!0,a,s)}else if(i!==t&&(o=!0,x.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(x(e),n)})),n))for(;u>l;l++)n(e[l],r,s?i:i.call(e[l],l,n(e[l],r)));return o?e:c?n.call(e):u?n(e[0],r):a},now:function(){return(new Date).getTime()},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}}),x.ready.promise=function(t){if(!n)if(n=x.Deferred(),"complete"===a.readyState)setTimeout(x.ready);else if(a.addEventListener)a.addEventListener("DOMContentLoaded",q,!1),e.addEventListener("load",q,!1);else{a.attachEvent("onreadystatechange",q),e.attachEvent("onload",q);var r=!1;try{r=null==e.frameElement&&a.documentElement}catch(i){}r&&r.doScroll&&function o(){if(!x.isReady){try{r.doScroll("left")}catch(e){return setTimeout(o,50)}_(),x.ready()}}()}return n.promise(t)},x.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){c["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=x.type(e);return x.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=x(a),function(e,t){var n,r,i,o,a,s,l,u,c,p,f,d,h,g,m,y,v,b="sizzle"+-new Date,w=e.document,T=0,C=0,N=st(),k=st(),E=st(),S=!1,A=function(e,t){return e===t?(S=!0,0):0},j=typeof t,D=1<<31,L={}.hasOwnProperty,H=[],q=H.pop,_=H.push,M=H.push,O=H.slice,F=H.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},B="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",P="[\\x20\\t\\r\\n\\f]",R="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",W=R.replace("w","w#"),$="\\["+P+"*("+R+")"+P+"*(?:([*^$|!~]?=)"+P+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+W+")|)|)"+P+"*\\]",I=":("+R+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+$.replace(3,8)+")*)|.*)\\)|)",z=RegExp("^"+P+"+|((?:^|[^\\\\])(?:\\\\.)*)"+P+"+$","g"),X=RegExp("^"+P+"*,"+P+"*"),U=RegExp("^"+P+"*([>+~]|"+P+")"+P+"*"),V=RegExp(P+"*[+~]"),Y=RegExp("="+P+"*([^\\]'\"]*)"+P+"*\\]","g"),J=RegExp(I),G=RegExp("^"+W+"$"),Q={ID:RegExp("^#("+R+")"),CLASS:RegExp("^\\.("+R+")"),TAG:RegExp("^("+R.replace("w","w*")+")"),ATTR:RegExp("^"+$),PSEUDO:RegExp("^"+I),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+P+"*(even|odd|(([+-]|)(\\d*)n|)"+P+"*(?:([+-]|)"+P+"*(\\d+)|))"+P+"*\\)|)","i"),bool:RegExp("^(?:"+B+")$","i"),needsContext:RegExp("^"+P+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+P+"*((?:-\\d)?\\d*)"+P+"*\\)|)(?=[^-]|$)","i")},K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,et=/^(?:input|select|textarea|button)$/i,tt=/^h\d$/i,nt=/'|\\/g,rt=RegExp("\\\\([\\da-f]{1,6}"+P+"?|("+P+")|.)","ig"),it=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(55296|r>>10,56320|1023&r)};try{M.apply(H=O.call(w.childNodes),w.childNodes),H[w.childNodes.length].nodeType}catch(ot){M={apply:H.length?function(e,t){_.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function at(e,t,n,i){var o,a,s,l,u,c,d,m,y,x;if((t?t.ownerDocument||t:w)!==f&&p(t),t=t||f,n=n||[],!e||"string"!=typeof e)return n;if(1!==(l=t.nodeType)&&9!==l)return[];if(h&&!i){if(o=Z.exec(e))if(s=o[1]){if(9===l){if(a=t.getElementById(s),!a||!a.parentNode)return n;if(a.id===s)return n.push(a),n}else if(t.ownerDocument&&(a=t.ownerDocument.getElementById(s))&&v(t,a)&&a.id===s)return n.push(a),n}else{if(o[2])return M.apply(n,t.getElementsByTagName(e)),n;if((s=o[3])&&r.getElementsByClassName&&t.getElementsByClassName)return M.apply(n,t.getElementsByClassName(s)),n}if(r.qsa&&(!g||!g.test(e))){if(m=d=b,y=t,x=9===l&&e,1===l&&"object"!==t.nodeName.toLowerCase()){c=mt(e),(d=t.getAttribute("id"))?m=d.replace(nt,"\\$&"):t.setAttribute("id",m),m="[id='"+m+"'] ",u=c.length;while(u--)c[u]=m+yt(c[u]);y=V.test(e)&&t.parentNode||t,x=c.join(",")}if(x)try{return M.apply(n,y.querySelectorAll(x)),n}catch(T){}finally{d||t.removeAttribute("id")}}}return kt(e.replace(z,"$1"),t,n,i)}function st(){var e=[];function t(n,r){return e.push(n+=" ")>o.cacheLength&&delete t[e.shift()],t[n]=r}return t}function lt(e){return e[b]=!0,e}function ut(e){var t=f.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function ct(e,t){var n=e.split("|"),r=e.length;while(r--)o.attrHandle[n[r]]=t}function pt(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||D)-(~e.sourceIndex||D);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function ft(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function dt(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function ht(e){return lt(function(t){return t=+t,lt(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}s=at.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},r=at.support={},p=at.setDocument=function(e){var n=e?e.ownerDocument||e:w,i=n.defaultView;return n!==f&&9===n.nodeType&&n.documentElement?(f=n,d=n.documentElement,h=!s(n),i&&i.attachEvent&&i!==i.top&&i.attachEvent("onbeforeunload",function(){p()}),r.attributes=ut(function(e){return e.className="i",!e.getAttribute("className")}),r.getElementsByTagName=ut(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),r.getElementsByClassName=ut(function(e){return e.innerHTML="<div class='a'></div><div class='a i'></div>",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),r.getById=ut(function(e){return d.appendChild(e).id=b,!n.getElementsByName||!n.getElementsByName(b).length}),r.getById?(o.find.ID=function(e,t){if(typeof t.getElementById!==j&&h){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){return e.getAttribute("id")===t}}):(delete o.find.ID,o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){var n=typeof e.getAttributeNode!==j&&e.getAttributeNode("id");return n&&n.value===t}}),o.find.TAG=r.getElementsByTagName?function(e,n){return typeof n.getElementsByTagName!==j?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},o.find.CLASS=r.getElementsByClassName&&function(e,n){return typeof n.getElementsByClassName!==j&&h?n.getElementsByClassName(e):t},m=[],g=[],(r.qsa=K.test(n.querySelectorAll))&&(ut(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||g.push("\\["+P+"*(?:value|"+B+")"),e.querySelectorAll(":checked").length||g.push(":checked")}),ut(function(e){var t=n.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("t",""),e.querySelectorAll("[t^='']").length&&g.push("[*^$]="+P+"*(?:''|\"\")"),e.querySelectorAll(":enabled").length||g.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),g.push(",.*:")})),(r.matchesSelector=K.test(y=d.webkitMatchesSelector||d.mozMatchesSelector||d.oMatchesSelector||d.msMatchesSelector))&&ut(function(e){r.disconnectedMatch=y.call(e,"div"),y.call(e,"[s!='']:x"),m.push("!=",I)}),g=g.length&&RegExp(g.join("|")),m=m.length&&RegExp(m.join("|")),v=K.test(d.contains)||d.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},A=d.compareDocumentPosition?function(e,t){if(e===t)return S=!0,0;var i=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t);return i?1&i||!r.sortDetached&&t.compareDocumentPosition(e)===i?e===n||v(w,e)?-1:t===n||v(w,t)?1:c?F.call(c,e)-F.call(c,t):0:4&i?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return S=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:c?F.call(c,e)-F.call(c,t):0;if(o===a)return pt(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?pt(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},n):f},at.matches=function(e,t){return at(e,null,null,t)},at.matchesSelector=function(e,t){if((e.ownerDocument||e)!==f&&p(e),t=t.replace(Y,"='$1']"),!(!r.matchesSelector||!h||m&&m.test(t)||g&&g.test(t)))try{var n=y.call(e,t);if(n||r.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(i){}return at(t,f,null,[e]).length>0},at.contains=function(e,t){return(e.ownerDocument||e)!==f&&p(e),v(e,t)},at.attr=function(e,n){(e.ownerDocument||e)!==f&&p(e);var i=o.attrHandle[n.toLowerCase()],a=i&&L.call(o.attrHandle,n.toLowerCase())?i(e,n,!h):t;return a===t?r.attributes||!h?e.getAttribute(n):(a=e.getAttributeNode(n))&&a.specified?a.value:null:a},at.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},at.uniqueSort=function(e){var t,n=[],i=0,o=0;if(S=!r.detectDuplicates,c=!r.sortStable&&e.slice(0),e.sort(A),S){while(t=e[o++])t===e[o]&&(i=n.push(o));while(i--)e.splice(n[i],1)}return e},a=at.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+=a(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=a(t);return n},o=at.selectors={cacheLength:50,createPseudo:lt,match:Q,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(rt,it),e[3]=(e[4]||e[5]||"").replace(rt,it),"~="===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]||at.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]&&at.error(e[0]),e},PSEUDO:function(e){var n,r=!e[5]&&e[2];return Q.CHILD.test(e[0])?null:(e[3]&&e[4]!==t?e[2]=e[4]:r&&J.test(r)&&(n=mt(r,!0))&&(n=r.indexOf(")",r.length-n)-r.length)&&(e[0]=e[0].slice(0,n),e[2]=r.slice(0,n)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(rt,it).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=N[e+" "];return t||(t=RegExp("(^|"+P+")"+e+"("+P+"|$)"))&&N(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==j&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=at.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,l){var u,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!l&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[b]||(m[b]={}),u=c[e]||[],d=u[0]===T&&u[1],f=u[0]===T&&u[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[T,d,f];break}}else if(v&&(u=(t[b]||(t[b]={}))[e])&&u[0]===T)f=u[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[b]||(p[b]={}))[e]=[T,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=o.pseudos[e]||o.setFilters[e.toLowerCase()]||at.error("unsupported pseudo: "+e);return r[b]?r(t):r.length>1?(n=[e,e,"",t],o.setFilters.hasOwnProperty(e.toLowerCase())?lt(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=F.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:lt(function(e){var t=[],n=[],r=l(e.replace(z,"$1"));return r[b]?lt(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:lt(function(e){return function(t){return at(e,t).length>0}}),contains:lt(function(e){return function(t){return(t.textContent||t.innerText||a(t)).indexOf(e)>-1}}),lang:lt(function(e){return G.test(e||"")||at.error("unsupported lang: "+e),e=e.replace(rt,it).toLowerCase(),function(t){var n;do if(n=h?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===d},focus:function(e){return e===f.activeElement&&(!f.hasFocus||f.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!o.pseudos.empty(e)},header:function(e){return tt.test(e.nodeName)},input:function(e){return et.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:ht(function(){return[0]}),last:ht(function(e,t){return[t-1]}),eq:ht(function(e,t,n){return[0>n?n+t:n]}),even:ht(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:ht(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:ht(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:ht(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}},o.pseudos.nth=o.pseudos.eq;for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})o.pseudos[n]=ft(n);for(n in{submit:!0,reset:!0})o.pseudos[n]=dt(n);function gt(){}gt.prototype=o.filters=o.pseudos,o.setFilters=new gt;function mt(e,t){var n,r,i,a,s,l,u,c=k[e+" "];if(c)return t?0:c.slice(0);s=e,l=[],u=o.preFilter;while(s){(!n||(r=X.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),l.push(i=[])),n=!1,(r=U.exec(s))&&(n=r.shift(),i.push({value:n,type:r[0].replace(z," ")}),s=s.slice(n.length));for(a in o.filter)!(r=Q[a].exec(s))||u[a]&&!(r=u[a](r))||(n=r.shift(),i.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?at.error(e):k(e,l).slice(0)}function yt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function vt(e,t,n){var r=t.dir,o=n&&"parentNode"===r,a=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||o)return e(t,n,i)}:function(t,n,s){var l,u,c,p=T+" "+a;if(s){while(t=t[r])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[r])if(1===t.nodeType||o)if(c=t[b]||(t[b]={}),(u=c[r])&&u[0]===p){if((l=u[1])===!0||l===i)return l===!0}else if(u=c[r]=[p],u[1]=e(t,n,s)||i,u[1]===!0)return!0}}function bt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function xt(e,t,n,r,i){var o,a=[],s=0,l=e.length,u=null!=t;for(;l>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),u&&t.push(s));return a}function wt(e,t,n,r,i,o){return r&&!r[b]&&(r=wt(r)),i&&!i[b]&&(i=wt(i,o)),lt(function(o,a,s,l){var u,c,p,f=[],d=[],h=a.length,g=o||Nt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:xt(g,f,e,s,l),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,l),r){u=xt(y,d),r(u,[],s,l),c=u.length;while(c--)(p=u[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){u=[],c=y.length;while(c--)(p=y[c])&&u.push(m[c]=p);i(null,y=[],u,l)}c=y.length;while(c--)(p=y[c])&&(u=i?F.call(o,p):f[c])>-1&&(o[u]=!(a[u]=p))}}else y=xt(y===a?y.splice(h,y.length):y),i?i(null,a,y,l):M.apply(a,y)})}function Tt(e){var t,n,r,i=e.length,a=o.relative[e[0].type],s=a||o.relative[" "],l=a?1:0,c=vt(function(e){return e===t},s,!0),p=vt(function(e){return F.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==u)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;i>l;l++)if(n=o.relative[e[l].type])f=[vt(bt(f),n)];else{if(n=o.filter[e[l].type].apply(null,e[l].matches),n[b]){for(r=++l;i>r;r++)if(o.relative[e[r].type])break;return wt(l>1&&bt(f),l>1&&yt(e.slice(0,l-1).concat({value:" "===e[l-2].type?"*":""})).replace(z,"$1"),n,r>l&&Tt(e.slice(l,r)),i>r&&Tt(e=e.slice(r)),i>r&&yt(e))}f.push(n)}return bt(f)}function Ct(e,t){var n=0,r=t.length>0,a=e.length>0,s=function(s,l,c,p,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,C=u,N=s||a&&o.find.TAG("*",d&&l.parentNode||l),k=T+=null==C?1:Math.random()||.1;for(w&&(u=l!==f&&l,i=n);null!=(h=N[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,l,c)){p.push(h);break}w&&(T=k,i=++n)}r&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,r&&b!==v){g=0;while(m=t[g++])m(x,y,l,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=q.call(p));y=xt(y)}M.apply(p,y),w&&!s&&y.length>0&&v+t.length>1&&at.uniqueSort(p)}return w&&(T=k,u=C),x};return r?lt(s):s}l=at.compile=function(e,t){var n,r=[],i=[],o=E[e+" "];if(!o){t||(t=mt(e)),n=t.length;while(n--)o=Tt(t[n]),o[b]?r.push(o):i.push(o);o=E(e,Ct(i,r))}return o};function Nt(e,t,n){var r=0,i=t.length;for(;i>r;r++)at(e,t[r],n);return n}function kt(e,t,n,i){var a,s,u,c,p,f=mt(e);if(!i&&1===f.length){if(s=f[0]=f[0].slice(0),s.length>2&&"ID"===(u=s[0]).type&&r.getById&&9===t.nodeType&&h&&o.relative[s[1].type]){if(t=(o.find.ID(u.matches[0].replace(rt,it),t)||[])[0],!t)return n;e=e.slice(s.shift().value.length)}a=Q.needsContext.test(e)?0:s.length;while(a--){if(u=s[a],o.relative[c=u.type])break;if((p=o.find[c])&&(i=p(u.matches[0].replace(rt,it),V.test(s[0].type)&&t.parentNode||t))){if(s.splice(a,1),e=i.length&&yt(s),!e)return M.apply(n,i),n;break}}}return l(e,f)(i,t,!h,n,V.test(e)),n}r.sortStable=b.split("").sort(A).join("")===b,r.detectDuplicates=S,p(),r.sortDetached=ut(function(e){return 1&e.compareDocumentPosition(f.createElement("div"))}),ut(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||ct("type|href|height|width",function(e,n,r){return r?t:e.getAttribute(n,"type"===n.toLowerCase()?1:2)}),r.attributes&&ut(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||ct("value",function(e,n,r){return r||"input"!==e.nodeName.toLowerCase()?t:e.defaultValue}),ut(function(e){return null==e.getAttribute("disabled")})||ct(B,function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&i.specified?i.value:e[n]===!0?n.toLowerCase():null}),x.find=at,x.expr=at.selectors,x.expr[":"]=x.expr.pseudos,x.unique=at.uniqueSort,x.text=at.getText,x.isXMLDoc=at.isXML,x.contains=at.contains}(e);var O={};function F(e){var t=O[e]={};return x.each(e.match(T)||[],function(e,n){t[n]=!0}),t}x.Callbacks=function(e){e="string"==typeof e?O[e]||F(e):x.extend({},e);var n,r,i,o,a,s,l=[],u=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=l.length,n=!0;l&&o>a;a++)if(l[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,l&&(u?u.length&&c(u.shift()):r?l=[]:p.disable())},p={add:function(){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this},remove:function(){return l&&x.each(arguments,function(e,t){var r;while((r=x.inArray(t,l,r))>-1)l.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?x.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],o=0,this},disable:function(){return l=u=r=t,this},disabled:function(){return!l},lock:function(){return u=t,r||p.disable(),this},locked:function(){return!u},fireWith:function(e,t){return!l||i&&!u||(t=t||[],t=[e,t.slice?t.slice():t],n?u.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},x.extend({Deferred:function(e){var t=[["resolve","done",x.Callbacks("once memory"),"resolved"],["reject","fail",x.Callbacks("once memory"),"rejected"],["notify","progress",x.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return x.Deferred(function(n){x.each(t,function(t,o){var a=o[0],s=x.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&x.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?x.extend(e,r):r}},i={};return r.pipe=r.then,x.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=g.call(arguments),r=n.length,i=1!==r||e&&x.isFunction(e.promise)?r:0,o=1===i?e:x.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?g.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,l,u;if(r>1)for(s=Array(r),l=Array(r),u=Array(r);r>t;t++)n[t]&&x.isFunction(n[t].promise)?n[t].promise().done(a(t,u,n)).fail(o.reject).progress(a(t,l,s)):--i;return i||o.resolveWith(u,n),o.promise()}}),x.support=function(t){var n,r,o,s,l,u,c,p,f,d=a.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=d.getElementsByTagName("*")||[],r=d.getElementsByTagName("a")[0],!r||!r.style||!n.length)return t;s=a.createElement("select"),u=s.appendChild(a.createElement("option")),o=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t.getSetAttribute="t"!==d.className,t.leadingWhitespace=3===d.firstChild.nodeType,t.tbody=!d.getElementsByTagName("tbody").length,t.htmlSerialize=!!d.getElementsByTagName("link").length,t.style=/top/.test(r.getAttribute("style")),t.hrefNormalized="/a"===r.getAttribute("href"),t.opacity=/^0.5/.test(r.style.opacity),t.cssFloat=!!r.style.cssFloat,t.checkOn=!!o.value,t.optSelected=u.selected,t.enctype=!!a.createElement("form").enctype,t.html5Clone="<:nav></:nav>"!==a.createElement("nav").cloneNode(!0).outerHTML,t.inlineBlockNeedsLayout=!1,t.shrinkWrapBlocks=!1,t.pixelPosition=!1,t.deleteExpando=!0,t.noCloneEvent=!0,t.reliableMarginRight=!0,t.boxSizingReliable=!0,o.checked=!0,t.noCloneChecked=o.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!u.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}o=a.createElement("input"),o.setAttribute("value",""),t.input=""===o.getAttribute("value"),o.value="t",o.setAttribute("type","radio"),t.radioValue="t"===o.value,o.setAttribute("checked","t"),o.setAttribute("name","t"),l=a.createDocumentFragment(),l.appendChild(o),t.appendChecked=o.checked,t.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip;for(f in x(t))break;return t.ownLast="0"!==f,x(function(){var n,r,o,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",l=a.getElementsByTagName("body")[0];l&&(n=a.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",l.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",o=d.getElementsByTagName("td"),o[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===o[0].offsetHeight,o[0].style.display="",o[1].style.display="none",t.reliableHiddenOffsets=p&&0===o[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",x.swap(l,null!=l.style.zoom?{zoom:1}:{},function(){t.boxSizing=4===d.offsetWidth}),e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(a.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="<div></div>",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(l.style.zoom=1)),l.removeChild(n),n=d=o=r=null)}),n=s=l=u=r=o=null,t }({});var B=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;function R(e,n,r,i){if(x.acceptData(e)){var o,a,s=x.expando,l=e.nodeType,u=l?x.cache:e,c=l?e[s]:e[s]&&s;if(c&&u[c]&&(i||u[c].data)||r!==t||"string"!=typeof n)return c||(c=l?e[s]=p.pop()||x.guid++:s),u[c]||(u[c]=l?{}:{toJSON:x.noop}),("object"==typeof n||"function"==typeof n)&&(i?u[c]=x.extend(u[c],n):u[c].data=x.extend(u[c].data,n)),a=u[c],i||(a.data||(a.data={}),a=a.data),r!==t&&(a[x.camelCase(n)]=r),"string"==typeof n?(o=a[n],null==o&&(o=a[x.camelCase(n)])):o=a,o}}function W(e,t,n){if(x.acceptData(e)){var r,i,o=e.nodeType,a=o?x.cache:e,s=o?e[x.expando]:x.expando;if(a[s]){if(t&&(r=n?a[s]:a[s].data)){x.isArray(t)?t=t.concat(x.map(t,x.camelCase)):t in r?t=[t]:(t=x.camelCase(t),t=t in r?[t]:t.split(" ")),i=t.length;while(i--)delete r[t[i]];if(n?!I(r):!x.isEmptyObject(r))return}(n||(delete a[s].data,I(a[s])))&&(o?x.cleanData([e],!0):x.support.deleteExpando||a!=a.window?delete a[s]:a[s]=null)}}}x.extend({cache:{},noData:{applet:!0,embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return e=e.nodeType?x.cache[e[x.expando]]:e[x.expando],!!e&&!I(e)},data:function(e,t,n){return R(e,t,n)},removeData:function(e,t){return W(e,t)},_data:function(e,t,n){return R(e,t,n,!0)},_removeData:function(e,t){return W(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&x.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),x.fn.extend({data:function(e,n){var r,i,o=null,a=0,s=this[0];if(e===t){if(this.length&&(o=x.data(s),1===s.nodeType&&!x._data(s,"parsedAttrs"))){for(r=s.attributes;r.length>a;a++)i=r[a].name,0===i.indexOf("data-")&&(i=x.camelCase(i.slice(5)),$(s,i,o[i]));x._data(s,"parsedAttrs",!0)}return o}return"object"==typeof e?this.each(function(){x.data(this,e)}):arguments.length>1?this.each(function(){x.data(this,e,n)}):s?$(s,e,x.data(s,e)):null},removeData:function(e){return this.each(function(){x.removeData(this,e)})}});function $(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(P,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:B.test(r)?x.parseJSON(r):r}catch(o){}x.data(e,n,r)}else r=t}return r}function I(e){var t;for(t in e)if(("data"!==t||!x.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}x.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=x._data(e,n),r&&(!i||x.isArray(r)?i=x._data(e,n,x.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=x.queue(e,t),r=n.length,i=n.shift(),o=x._queueHooks(e,t),a=function(){x.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 x._data(e,n)||x._data(e,n,{empty:x.Callbacks("once memory").add(function(){x._removeData(e,t+"queue"),x._removeData(e,n)})})}}),x.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?x.queue(this[0],e):n===t?this:this.each(function(){var t=x.queue(this,e,n);x._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&x.dequeue(this,e)})},dequeue:function(e){return this.each(function(){x.dequeue(this,e)})},delay:function(e,t){return e=x.fx?x.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=x.Deferred(),a=this,s=this.length,l=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=x._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(l));return l(),o.promise(n)}});var z,X,U=/[\t\r\n\f]/g,V=/\r/g,Y=/^(?:input|select|textarea|button|object)$/i,J=/^(?:a|area)$/i,G=/^(?:checked|selected)$/i,Q=x.support.getSetAttribute,K=x.support.input;x.fn.extend({attr:function(e,t){return x.access(this,x.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){x.removeAttr(this,e)})},prop:function(e,t){return x.access(this,x.prop,e,t,arguments.length>1)},removeProp:function(e){return e=x.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,l="string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).addClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=x.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,l=0===arguments.length||"string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).removeClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?x.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):x.isFunction(e)?this.each(function(n){x(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var t,r=0,o=x(this),a=e.match(T)||[];while(t=a[r++])o.hasClass(t)?o.removeClass(t):o.addClass(t)}else(n===i||"boolean"===n)&&(this.className&&x._data(this,"__className__",this.className),this.className=this.className||e===!1?"":x._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(U," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=x.isFunction(e),this.each(function(n){var o;1===this.nodeType&&(o=i?e.call(this,n,x(this).val()):e,null==o?o="":"number"==typeof o?o+="":x.isArray(o)&&(o=x.map(o,function(e){return null==e?"":e+""})),r=x.valHooks[this.type]||x.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=x.valHooks[o.type]||x.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(V,""):null==n?"":n)}}}),x.extend({valHooks:{option:{get:function(e){var t=x.find.attr(e,"value");return null!=t?t:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,l=0>i?s:o?i:0;for(;s>l;l++)if(n=r[l],!(!n.selected&&l!==i||(x.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&x.nodeName(n.parentNode,"optgroup"))){if(t=x(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n,r,i=e.options,o=x.makeArray(t),a=i.length;while(a--)r=i[a],(r.selected=x.inArray(x(r).val(),o)>=0)&&(n=!0);return n||(e.selectedIndex=-1),o}}},attr:function(e,n,r){var o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return typeof e.getAttribute===i?x.prop(e,n,r):(1===s&&x.isXMLDoc(e)||(n=n.toLowerCase(),o=x.attrHooks[n]||(x.expr.match.bool.test(n)?X:z)),r===t?o&&"get"in o&&null!==(a=o.get(e,n))?a:(a=x.find.attr(e,n),null==a?t:a):null!==r?o&&"set"in o&&(a=o.set(e,r,n))!==t?a:(e.setAttribute(n,r+""),r):(x.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(T);if(o&&1===e.nodeType)while(n=o[i++])r=x.propFix[n]||n,x.expr.match.bool.test(n)?K&&Q||!G.test(n)?e[r]=!1:e[x.camelCase("default-"+n)]=e[r]=!1:x.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!x.support.radioValue&&"radio"===t&&x.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!x.isXMLDoc(e),a&&(n=x.propFix[n]||n,o=x.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 t=x.find.attr(e,"tabindex");return t?parseInt(t,10):Y.test(e.nodeName)||J.test(e.nodeName)&&e.href?0:-1}}}}),X={set:function(e,t,n){return t===!1?x.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&x.propFix[n]||n,n):e[x.camelCase("default-"+n)]=e[n]=!0,n}},x.each(x.expr.match.bool.source.match(/\w+/g),function(e,n){var r=x.expr.attrHandle[n]||x.find.attr;x.expr.attrHandle[n]=K&&Q||!G.test(n)?function(e,n,i){var o=x.expr.attrHandle[n],a=i?t:(x.expr.attrHandle[n]=t)!=r(e,n,i)?n.toLowerCase():null;return x.expr.attrHandle[n]=o,a}:function(e,n,r){return r?t:e[x.camelCase("default-"+n)]?n.toLowerCase():null}}),K&&Q||(x.attrHooks.value={set:function(e,n,r){return x.nodeName(e,"input")?(e.defaultValue=n,t):z&&z.set(e,n,r)}}),Q||(z={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}},x.expr.attrHandle.id=x.expr.attrHandle.name=x.expr.attrHandle.coords=function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&""!==i.value?i.value:null},x.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&r.specified?r.value:t},set:z.set},x.attrHooks.contenteditable={set:function(e,t,n){z.set(e,""===t?!1:t,n)}},x.each(["width","height"],function(e,n){x.attrHooks[n]={set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}}})),x.support.hrefNormalized||x.each(["href","src"],function(e,t){x.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),x.support.style||(x.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),x.support.optSelected||(x.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}}),x.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){x.propFix[this.toLowerCase()]=this}),x.support.enctype||(x.propFix.enctype="encoding"),x.each(["radio","checkbox"],function(){x.valHooks[this]={set:function(e,n){return x.isArray(n)?e.checked=x.inArray(x(e).val(),n)>=0:t}},x.support.checkOn||(x.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}function at(){try{return a.activeElement}catch(e){}}x.event={global:{},add:function(e,n,r,o,a){var s,l,u,c,p,f,d,h,g,m,y,v=x._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=x.guid++),(l=v.events)||(l=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof x===i||e&&x.event.triggered===e.type?t:x.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(T)||[""],u=n.length;while(u--)s=rt.exec(n[u])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),g&&(p=x.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=x.event.special[g]||{},d=x.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&x.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=l[g])||(h=l[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),x.event.global[g]=!0);e=null}},remove:function(e,t,n,r,i){var o,a,s,l,u,c,p,f,d,h,g,m=x.hasData(e)&&x._data(e);if(m&&(c=m.events)){t=(t||"").match(T)||[""],u=t.length;while(u--)if(s=rt.exec(t[u])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=x.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));l&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||x.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)x.event.remove(e,d+t[u],n,r,!0);x.isEmptyObject(c)&&(delete m.handle,x._removeData(e,"events"))}},trigger:function(n,r,i,o){var s,l,u,c,p,f,d,h=[i||a],g=v.call(n,"type")?n.type:n,m=v.call(n,"namespace")?n.namespace.split("."):[];if(u=f=i=i||a,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+x.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),l=0>g.indexOf(":")&&"on"+g,n=n[x.expando]?n:new x.Event(g,"object"==typeof n&&n),n.isTrigger=o?2:3,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:x.makeArray(r,[n]),p=x.event.special[g]||{},o||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!o&&!p.noBubble&&!x.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(u=u.parentNode);u;u=u.parentNode)h.push(u),f=u;f===(i.ownerDocument||a)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((u=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(x._data(u,"events")||{})[n.type]&&x._data(u,"handle"),s&&s.apply(u,r),s=l&&u[l],s&&x.acceptData(u)&&s.apply&&s.apply(u,r)===!1&&n.preventDefault();if(n.type=g,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(h.pop(),r)===!1)&&x.acceptData(i)&&l&&i[g]&&!x.isWindow(i)){f=i[l],f&&(i[l]=null),x.event.triggered=g;try{i[g]()}catch(y){}x.event.triggered=t,f&&(i[l]=f)}return n.result}},dispatch:function(e){e=x.event.fix(e);var n,r,i,o,a,s=[],l=g.call(arguments),u=(x._data(this,"events")||{})[e.type]||[],c=x.event.special[e.type]||{};if(l[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=x.event.handlers.call(this,e,u),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((x.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,l),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],l=n.delegateCount,u=e.target;if(l&&u.nodeType&&(!e.button||"click"!==e.type))for(;u!=this;u=u.parentNode||this)if(1===u.nodeType&&(u.disabled!==!0||"click"!==e.type)){for(o=[],a=0;l>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?x(r,this).index(u)>=0:x.find(r,this,null,[u]).length),o[r]&&o.push(i);o.length&&s.push({elem:u,handlers:o})}return n.length>l&&s.push({elem:this,handlers:n.slice(l)}),s},fix:function(e){if(e[x.expando])return e;var t,n,r,i=e.type,o=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new x.Event(o),t=r.length;while(t--)n=r[t],e[n]=o[n];return e.target||(e.target=o.srcElement||a),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){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,s=n.button,l=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||a,o=i.documentElement,r=i.body,e.pageX=n.clientX+(o&&o.scrollLeft||r&&r.scrollLeft||0)-(o&&o.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(o&&o.scrollTop||r&&r.scrollTop||0)-(o&&o.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&l&&(e.relatedTarget=l===e.target?n.toElement:l),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==at()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===at()&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},click:{trigger:function(){return x.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t},_default:function(e){return x.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=x.extend(new x.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?x.event.trigger(i,null,t):x.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},x.removeEvent=a.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},x.Event=function(e,n){return this instanceof x.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&x.extend(this,n),this.timeStamp=e&&e.timeStamp||x.now(),this[x.expando]=!0,t):new x.Event(e,n)},x.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},x.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){x.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!x.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),x.support.submitBubbles||(x.event.special.submit={setup:function(){return x.nodeName(this,"form")?!1:(x.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=x.nodeName(n,"input")||x.nodeName(n,"button")?n.form:t;r&&!x._data(r,"submitBubbles")&&(x.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),x._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&x.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return x.nodeName(this,"form")?!1:(x.event.remove(this,"._submit"),t)}}),x.support.changeBubbles||(x.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(x.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),x.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),x.event.simulate("change",this,e,!0)})),!1):(x.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!x._data(t,"changeBubbles")&&(x.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||x.event.simulate("change",this.parentNode,e,!0)}),x._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 x.event.remove(this,"._change"),!Z.test(this.nodeName)}}),x.support.focusinBubbles||x.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){x.event.simulate(t,e.target,x.event.fix(e),!0)};x.event.special[t]={setup:function(){0===n++&&a.addEventListener(e,r,!0)},teardown:function(){0===--n&&a.removeEventListener(e,r,!0)}}}),x.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return x().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=x.guid++)),this.each(function(){x.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,x(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){x.event.remove(this,e,r,n)})},trigger:function(e,t){return this.each(function(){x.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?x.event.trigger(e,n,r,!0):t}});var st=/^.[^:#\[\.,]*$/,lt=/^(?:parents|prev(?:Until|All))/,ut=x.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};x.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(x(e).filter(function(){for(t=0;i>t;t++)if(x.contains(r[t],this))return!0}));for(t=0;i>t;t++)x.find(e,r[t],n);return n=this.pushStack(i>1?x.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},has:function(e){var t,n=x(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(x.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e||[],!0))},filter:function(e){return this.pushStack(ft(this,e||[],!1))},is:function(e){return!!ft(this,"string"==typeof e&&ut.test(e)?x(e):e||[],!1).length},closest:function(e,t){var n,r=0,i=this.length,o=[],a=ut.test(e)||"string"!=typeof e?x(e,t||this.context):0;for(;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(11>n.nodeType&&(a?a.index(n)>-1:1===n.nodeType&&x.find.matchesSelector(n,e))){n=o.push(n);break}return this.pushStack(o.length>1?x.unique(o):o)},index:function(e){return e?"string"==typeof e?x.inArray(this[0],x(e)):x.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?x(e,t):x.makeArray(e&&e.nodeType?[e]:e),r=x.merge(this.get(),n);return this.pushStack(x.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}x.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return x.dir(e,"parentNode")},parentsUntil:function(e,t,n){return x.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return x.dir(e,"nextSibling")},prevAll:function(e){return x.dir(e,"previousSibling")},nextUntil:function(e,t,n){return x.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return x.dir(e,"previousSibling",n)},siblings:function(e){return x.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return x.sibling(e.firstChild)},contents:function(e){return x.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:x.merge([],e.childNodes)}},function(e,t){x.fn[e]=function(n,r){var i=x.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=x.filter(r,i)),this.length>1&&(ct[e]||(i=x.unique(i)),lt.test(e)&&(i=i.reverse())),this.pushStack(i)}}),x.extend({filter:function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?x.find.matchesSelector(r,e)?[r]:[]:x.find.matches(e,x.grep(t,function(e){return 1===e.nodeType}))},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!x(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(x.isFunction(t))return x.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return x.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(st.test(t))return x.filter(t,e,n);t=x.filter(t,e)}return x.grep(e,function(e){return x.inArray(e,t)>=0!==n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/<tbody/i,wt=/<|&#?\w+;/,Tt=/<(?:script|style|link)/i,Ct=/^(?:checkbox|radio)$/i,Nt=/checked\s*(?:[^=]|=\s*.checked.)/i,kt=/^$|\/(?:java|ecma)script/i,Et=/^true\/(.*)/,St=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,At={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:x.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(a),Dt=jt.appendChild(a.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,x.fn.extend({text:function(e){return x.access(this,function(e){return e===t?x.text(this):this.empty().append((this[0]&&this[0].ownerDocument||a).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=Lt(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=Lt(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){var n,r=e?x.filter(e,this):this,i=0;for(;null!=(n=r[i]);i++)t||1!==n.nodeType||x.cleanData(Ft(n)),n.parentNode&&(t&&x.contains(n.ownerDocument,n)&&_t(Ft(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&x.cleanData(Ft(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&x.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 x.clone(this,e,t)})},html:function(e){return x.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!x.support.htmlSerialize&&mt.test(e)||!x.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(x.cleanData(Ft(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=x.map(this,function(e){return[e.nextSibling,e.parentNode]}),t=0;return this.domManip(arguments,function(n){var r=e[t++],i=e[t++];i&&(r&&r.parentNode!==i&&(r=this.nextSibling),x(this).remove(),i.insertBefore(n,r))},!0),t?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t,n){e=d.apply([],e);var r,i,o,a,s,l,u=0,c=this.length,p=this,f=c-1,h=e[0],g=x.isFunction(h);if(g||!(1>=c||"string"!=typeof h||x.support.checkClone)&&Nt.test(h))return this.each(function(r){var i=p.eq(r);g&&(e[0]=h.call(this,r,i.html())),i.domManip(e,t,n)});if(c&&(l=x.buildFragment(e,this[0].ownerDocument,!1,!n&&this),r=l.firstChild,1===l.childNodes.length&&(l=r),r)){for(a=x.map(Ft(l,"script"),Ht),o=a.length;c>u;u++)i=l,u!==f&&(i=x.clone(i,!0,!0),o&&x.merge(a,Ft(i,"script"))),t.call(this[u],i,u);if(o)for(s=a[a.length-1].ownerDocument,x.map(a,qt),u=0;o>u;u++)i=a[u],kt.test(i.type||"")&&!x._data(i,"globalEval")&&x.contains(s,i)&&(i.src?x._evalUrl(i.src):x.globalEval((i.text||i.textContent||i.innerHTML||"").replace(St,"")));l=r=null}return this}});function Lt(e,t){return x.nodeName(e,"table")&&x.nodeName(1===t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function Ht(e){return e.type=(null!==x.find.attr(e,"type"))+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function _t(e,t){var n,r=0;for(;null!=(n=e[r]);r++)x._data(n,"globalEval",!t||x._data(t[r],"globalEval"))}function Mt(e,t){if(1===t.nodeType&&x.hasData(e)){var n,r,i,o=x._data(e),a=x._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++)x.event.add(t,n,s[n][r])}a.data&&(a.data=x.extend({},a.data))}}function Ot(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!x.support.noCloneEvent&&t[x.expando]){i=x._data(t);for(r in i.events)x.removeEvent(t,r,i.handle);t.removeAttribute(x.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),x.support.html5Clone&&e.innerHTML&&!x.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Ct.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)}}x.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){x.fn[e]=function(e){var n,r=0,i=[],o=x(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),x(o[r])[t](n),h.apply(i,n.get());return this.pushStack(i)}});function Ft(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||x.nodeName(o,n)?s.push(o):x.merge(s,Ft(o,n));return n===t||n&&x.nodeName(e,n)?x.merge([e],s):s}function Bt(e){Ct.test(e.type)&&(e.defaultChecked=e.checked)}x.extend({clone:function(e,t,n){var r,i,o,a,s,l=x.contains(e.ownerDocument,e);if(x.support.html5Clone||x.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(x.support.noCloneEvent&&x.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||x.isXMLDoc(e)))for(r=Ft(o),s=Ft(e),a=0;null!=(i=s[a]);++a)r[a]&&Ot(i,r[a]);if(t)if(n)for(s=s||Ft(e),r=r||Ft(o),a=0;null!=(i=s[a]);a++)Mt(i,r[a]);else Mt(e,o);return r=Ft(o,"script"),r.length>0&&_t(r,!l&&Ft(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,l,u,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===x.type(o))x.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),l=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[l]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!x.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!x.support.tbody){o="table"!==l||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)x.nodeName(u=o.childNodes[i],"tbody")&&!u.childNodes.length&&o.removeChild(u)}x.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),x.support.appendChecked||x.grep(Ft(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===x.inArray(o,r))&&(a=x.contains(o.ownerDocument,o),s=Ft(f.appendChild(o),"script"),a&&_t(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,l=x.expando,u=x.cache,c=x.support.deleteExpando,f=x.event.special;for(;null!=(n=e[s]);s++)if((t||x.acceptData(n))&&(o=n[l],a=o&&u[o])){if(a.events)for(r in a.events)f[r]?x.event.remove(n,r):x.removeEvent(n,r,a.handle); u[o]&&(delete u[o],c?delete n[l]:typeof n.removeAttribute!==i?n.removeAttribute(l):n[l]=null,p.push(o))}},_evalUrl:function(e){return x.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})}}),x.fn.extend({wrapAll:function(e){if(x.isFunction(e))return this.each(function(t){x(this).wrapAll(e.call(this,t))});if(this[0]){var t=x(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return x.isFunction(e)?this.each(function(t){x(this).wrapInner(e.call(this,t))}):this.each(function(){var t=x(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=x.isFunction(e);return this.each(function(n){x(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){x.nodeName(this,"body")||x(this).replaceWith(this.childNodes)}).end()}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+w+")(.*)$","i"),Yt=RegExp("^("+w+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+w+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===x.css(e,"display")||!x.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=x._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=x._data(r,"olddisplay",ln(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&x._data(r,"olddisplay",i?n:x.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}x.fn.extend({css:function(e,n){return x.access(this,function(e,n,r){var i,o,a={},s=0;if(x.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=x.css(e,n[s],!1,o);return a}return r!==t?x.style(e,n,r):x.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){nn(this)?x(this).show():x(this).hide()})}}),x.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":x.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,l=x.camelCase(n),u=e.style;if(n=x.cssProps[l]||(x.cssProps[l]=tn(u,l)),s=x.cssHooks[n]||x.cssHooks[l],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:u[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(x.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||x.cssNumber[l]||(r+="px"),x.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(u[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{u[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,l=x.camelCase(n);return n=x.cssProps[l]||(x.cssProps[l]=tn(e.style,l)),s=x.cssHooks[n]||x.cssHooks[l],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||x.isNumeric(o)?o||0:a):a}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s.getPropertyValue(n)||s[n]:t,u=e.style;return s&&(""!==l||x.contains(e.ownerDocument,e)||(l=x.style(e,n)),Yt.test(l)&&Ut.test(n)&&(i=u.width,o=u.minWidth,a=u.maxWidth,u.minWidth=u.maxWidth=u.width=l,l=s.width,u.width=i,u.minWidth=o,u.maxWidth=a)),l}):a.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s[n]:t,u=e.style;return null==l&&u&&u[n]&&(l=u[n]),Yt.test(l)&&!zt.test(n)&&(i=u.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),u.left="fontSize"===n?"1em":l,l=u.pixelLeft+"px",u.left=i,a&&(o.left=a)),""===l?"auto":l});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=x.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=x.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=x.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=x.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=x.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(x.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function ln(e){var t=a,n=Gt[e];return n||(n=un(e,t),"none"!==n&&n||(Pt=(Pt||x("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=un(e,t),Pt.detach()),Gt[e]=n),n}function un(e,t){var n=x(t.createElement(e)).appendTo(t.body),r=x.css(n[0],"display");return n.remove(),r}x.each(["height","width"],function(e,n){x.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(x.css(e,"display"))?x.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,i),i):0)}}}),x.support.opacity||(x.cssHooks.opacity={get:function(e,t){return It.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=x.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===x.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),x(function(){x.support.reliableMarginRight||(x.cssHooks.marginRight={get:function(e,n){return n?x.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!x.support.pixelPosition&&x.fn.position&&x.each(["top","left"],function(e,n){x.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?x(e).position()[n]+"px":r):t}}})}),x.expr&&x.expr.filters&&(x.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!x.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||x.css(e,"display"))},x.expr.filters.visible=function(e){return!x.expr.filters.hidden(e)}),x.each({margin:"",padding:"",border:"Width"},function(e,t){x.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(x.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;x.fn.extend({serialize:function(){return x.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=x.prop(this,"elements");return e?x.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!x(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Ct.test(e))}).map(function(e,t){var n=x(this).val();return null==n?null:x.isArray(n)?x.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),x.param=function(e,n){var r,i=[],o=function(e,t){t=x.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=x.ajaxSettings&&x.ajaxSettings.traditional),x.isArray(e)||e.jquery&&!x.isPlainObject(e))x.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(x.isArray(t))x.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==x.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}x.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){x.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),x.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 mn,yn,vn=x.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Cn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Nn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=x.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=o.href}catch(Ln){yn=a.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(T)||[];if(x.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(l){var u;return o[l]=!0,x.each(e[l]||[],function(e,l){var c=l(n,r,i);return"string"!=typeof c||a||o[c]?a?!(u=c):t:(n.dataTypes.unshift(c),s(c),!1)}),u}return s(n.dataTypes[0])||!o["*"]&&s("*")}function _n(e,n){var r,i,o=x.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&x.extend(!0,e,r),e}x.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,l=e.indexOf(" ");return l>=0&&(i=e.slice(l,e.length),e=e.slice(0,l)),x.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&x.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?x("<div>").append(x.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},x.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){x.fn[t]=function(e){return this.on(t,e)}}),x.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Cn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":x.parseJSON,"text xml":x.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?_n(_n(e,x.ajaxSettings),t):_n(x.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,l,u,c,p=x.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?x(f):x.event,h=x.Deferred(),g=x.Callbacks("once memory"),m=p.statusCode||{},y={},v={},b=0,w="canceled",C={readyState:0,getResponseHeader:function(e){var t;if(2===b){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===b?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return b||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return b||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>b)for(t in e)m[t]=[m[t],e[t]];else C.always(e[C.status]);return this},abort:function(e){var t=e||w;return u&&u.abort(t),k(0,t),this}};if(h.promise(C).complete=g.add,C.success=C.done,C.error=C.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=x.trim(p.dataType||"*").toLowerCase().match(T)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(mn[3]||("http:"===mn[1]?"80":"443")))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=x.param(p.data,p.traditional)),qn(An,p,n,C),2===b)return C;l=p.global,l&&0===x.active++&&x.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Nn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(x.lastModified[o]&&C.setRequestHeader("If-Modified-Since",x.lastModified[o]),x.etag[o]&&C.setRequestHeader("If-None-Match",x.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&C.setRequestHeader("Content-Type",p.contentType),C.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)C.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,C,p)===!1||2===b))return C.abort();w="abort";for(i in{success:1,error:1,complete:1})C[i](p[i]);if(u=qn(jn,p,n,C)){C.readyState=1,l&&d.trigger("ajaxSend",[C,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){C.abort("timeout")},p.timeout));try{b=1,u.send(y,k)}catch(N){if(!(2>b))throw N;k(-1,N)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,N=n;2!==b&&(b=2,s&&clearTimeout(s),u=t,a=i||"",C.readyState=e>0?4:0,c=e>=200&&300>e||304===e,r&&(w=Mn(p,C,r)),w=On(p,w,C,c),c?(p.ifModified&&(T=C.getResponseHeader("Last-Modified"),T&&(x.lastModified[o]=T),T=C.getResponseHeader("etag"),T&&(x.etag[o]=T)),204===e||"HEAD"===p.type?N="nocontent":304===e?N="notmodified":(N=w.state,y=w.data,v=w.error,c=!v)):(v=N,(e||!N)&&(N="error",0>e&&(e=0))),C.status=e,C.statusText=(n||N)+"",c?h.resolveWith(f,[y,N,C]):h.rejectWith(f,[C,N,v]),C.statusCode(m),m=t,l&&d.trigger(c?"ajaxSuccess":"ajaxError",[C,p,c?y:v]),g.fireWith(f,[C,N]),l&&(d.trigger("ajaxComplete",[C,p]),--x.active||x.event.trigger("ajaxStop")))}return C},getJSON:function(e,t,n){return x.get(e,t,n,"json")},getScript:function(e,n){return x.get(e,t,n,"script")}}),x.each(["get","post"],function(e,n){x[n]=function(e,r,i,o){return x.isFunction(r)&&(o=o||i,i=r,r=t),x.ajax({url:e,type:n,dataType:o,data:r,success:i})}});function Mn(e,n,r){var i,o,a,s,l=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in l)if(l[s]&&l[s].test(o)){u.unshift(s);break}if(u[0]in r)a=u[0];else{for(s in r){if(!u[0]||e.converters[s+" "+u[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==u[0]&&u.unshift(a),r[a]):t}function On(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];o=c.shift();while(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(p){return{state:"parsererror",error:a?p:"No conversion from "+l+" to "+o}}}return{state:"success",data:t}}x.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return x.globalEval(e),e}}}),x.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),x.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=a.head||x("head")[0]||a.documentElement;return{send:function(t,i){n=a.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 Fn=[],Bn=/(=)\?(?=&|$)|\?\?/;x.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Fn.pop()||x.expando+"_"+vn++;return this[e]=!0,e}}),x.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,l=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return l||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=x.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,l?n[l]=n[l].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||x.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,Fn.push(o)),s&&x.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}x.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=x.ajaxSettings.xhr(),x.support.cors=!!Rn&&"withCredentials"in Rn,Rn=x.support.ajax=!!Rn,Rn&&x.ajaxTransport(function(n){if(!n.crossDomain||x.support.cors){var r;return{send:function(i,o){var a,s,l=n.xhr();if(n.username?l.open(n.type,n.url,n.async,n.username,n.password):l.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)l[s]=n.xhrFields[s];n.mimeType&&l.overrideMimeType&&l.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)l.setRequestHeader(s,i[s])}catch(u){}l.send(n.hasContent&&n.data||null),r=function(e,i){var s,u,c,p;try{if(r&&(i||4===l.readyState))if(r=t,a&&(l.onreadystatechange=x.noop,$n&&delete Pn[a]),i)4!==l.readyState&&l.abort();else{p={},s=l.status,u=l.getAllResponseHeaders(),"string"==typeof l.responseText&&(p.text=l.responseText);try{c=l.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,u)},n.async?4===l.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},x(e).unload($n)),Pn[a]=r),l.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+w+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n=this.createTween(e,t),r=n.cur(),i=Yn.exec(t),o=i&&i[3]||(x.cssNumber[e]?"":"px"),a=(x.cssNumber[e]||"px"!==o&&+r)&&Yn.exec(x.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,x.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}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=x.now()}function Zn(e,t,n){var r,i=(Qn[t]||[]).concat(Qn["*"]),o=0,a=i.length;for(;a>o;o++)if(r=i[o].call(n,t,e))return r}function er(e,t,n){var r,i,o=0,a=Gn.length,s=x.Deferred().always(function(){delete l.elem}),l=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,u.startTime+u.duration-t),r=n/u.duration||0,o=1-r,a=0,l=u.tweens.length;for(;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:x.extend({},t),opts:x.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=x.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(tr(c,u.opts.specialEasing);a>o;o++)if(r=Gn[o].call(u,e,c,u.opts))return r;return x.map(c,Zn,u),x.isFunction(u.opts.start)&&u.opts.start.call(e,u),x.fx.timer(x.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 tr(e,t){var n,r,i,o,a;for(n in e)if(r=x.camelCase(n),i=t[r],o=e[n],x.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),a=x.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}x.Animation=x.extend(er,{tweener:function(e,t){x.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,l,u=this,c={},p=e.style,f=e.nodeType&&nn(e),d=x._data(e,"fxshow");n.queue||(s=x._queueHooks(e,"fx"),null==s.unqueued&&(s.unqueued=0,l=s.empty.fire,s.empty.fire=function(){s.unqueued||l()}),s.unqueued++,u.always(function(){u.always(function(){s.unqueued--,x.queue(e,"fx").length||s.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],"inline"===x.css(e,"display")&&"none"===x.css(e,"float")&&(x.support.inlineBlockNeedsLayout&&"inline"!==ln(e.nodeName)?p.zoom=1:p.display="inline-block")),n.overflow&&(p.overflow="hidden",x.support.shrinkWrapBlocks||u.always(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t)if(i=t[r],Vn.exec(i)){if(delete t[r],o=o||"toggle"===i,i===(f?"hide":"show"))continue;c[r]=d&&d[r]||x.style(e,r)}if(!x.isEmptyObject(c)){d?"hidden"in d&&(f=d.hidden):d=x._data(e,"fxshow",{}),o&&(d.hidden=!f),f?x(e).show():u.done(function(){x(e).hide()}),u.done(function(){var t;x._removeData(e,"fxshow");for(t in c)x.style(e,t,c[t])});for(r in c)a=Zn(f?d[r]:0,r,u),r in d||(d[r]=a.start,f&&(a.end=a.start,a.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}x.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(x.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?x.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=x.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){x.fx.step[e.prop]?x.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[x.cssProps[e.prop]]||x.cssHooks[e.prop])?x.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},x.each(["toggle","show","hide"],function(e,t){var n=x.fn[t];x.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),x.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=x.isEmptyObject(e),o=x.speed(t,n,r),a=function(){var t=er(this,x.extend({},e),o);(i||x._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=x.timers,a=x._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&x.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=x._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=x.timers,a=r?r.length:0;for(n.finish=!0,x.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})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}x.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){x.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),x.speed=function(e,t,n){var r=e&&"object"==typeof e?x.extend({},e):{complete:n||!n&&t||x.isFunction(e)&&e,duration:e,easing:n&&t||t&&!x.isFunction(t)&&t};return r.duration=x.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in x.fx.speeds?x.fx.speeds[r.duration]:x.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){x.isFunction(r.old)&&r.old.call(this),r.queue&&x.dequeue(this,r.queue)},r},x.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},x.timers=[],x.fx=rr.prototype.init,x.fx.tick=function(){var e,n=x.timers,r=0;for(Xn=x.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||x.fx.stop(),Xn=t},x.fx.timer=function(e){e()&&x.timers.push(e)&&x.fx.start()},x.fx.interval=13,x.fx.start=function(){Un||(Un=setInterval(x.fx.tick,x.fx.interval))},x.fx.stop=function(){clearInterval(Un),Un=null},x.fx.speeds={slow:600,fast:200,_default:400},x.fx.step={},x.expr&&x.expr.filters&&(x.expr.filters.animated=function(e){return x.grep(x.timers,function(t){return e===t.elem}).length}),x.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){x.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,x.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},x.offset={setOffset:function(e,t,n){var r=x.css(e,"position");"static"===r&&(e.style.position="relative");var i=x(e),o=i.offset(),a=x.css(e,"top"),s=x.css(e,"left"),l=("absolute"===r||"fixed"===r)&&x.inArray("auto",[a,s])>-1,u={},c={},p,f;l?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),x.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(u.top=t.top-o.top+p),null!=t.left&&(u.left=t.left-o.left+f),"using"in t?t.using.call(e,u):i.css(u)}},x.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===x.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),x.nodeName(e[0],"html")||(n=e.offset()),n.top+=x.css(e[0],"borderTopWidth",!0),n.left+=x.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-x.css(r,"marginTop",!0),left:t.left-n.left-x.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||s;while(e&&!x.nodeName(e,"html")&&"static"===x.css(e,"position"))e=e.offsetParent;return e||s})}}),x.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);x.fn[e]=function(i){return x.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?x(a).scrollLeft():o,r?o:x(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return x.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}x.each({Height:"height",Width:"width"},function(e,n){x.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){x.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return x.access(this,function(n,r,i){var o;return x.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?x.css(n,r,s):x.style(n,r,i,s)},n,a?i:t,a,null)}})}),x.fn.size=function(){return this.length},x.fn.andSelf=x.fn.addBack,"object"==typeof module&&module&&"object"==typeof module.exports?module.exports=x:(e.jQuery=e.$=x,"function"==typeof define&&define.amd&&define("jquery",[],function(){return x}))})(window); /*! jQuery Migrate v1.2.1 | (c) 2005, 2013 jQuery Foundation, Inc. and other contributors | jquery.org/license */ jQuery.migrateMute===void 0&&(jQuery.migrateMute=!0),function(e,t,n){function r(n){var r=t.console;i[n]||(i[n]=!0,e.migrateWarnings.push(n),r&&r.warn&&!e.migrateMute&&(r.warn("JQMIGRATE: "+n),e.migrateTrace&&r.trace&&r.trace()))}function a(t,a,i,o){if(Object.defineProperty)try{return Object.defineProperty(t,a,{configurable:!0,enumerable:!0,get:function(){return r(o),i},set:function(e){r(o),i=e}}),n}catch(s){}e._definePropertyBroken=!0,t[a]=i}var i={};e.migrateWarnings=[],!e.migrateMute&&t.console&&t.console.log&&t.console.log("JQMIGRATE: Logging is active"),e.migrateTrace===n&&(e.migrateTrace=!0),e.migrateReset=function(){i={},e.migrateWarnings.length=0},"BackCompat"===document.compatMode&&r("jQuery is not compatible with Quirks Mode");var o=e("<input/>",{size:1}).attr("size")&&e.attrFn,s=e.attr,u=e.attrHooks.value&&e.attrHooks.value.get||function(){return null},c=e.attrHooks.value&&e.attrHooks.value.set||function(){return n},l=/^(?:input|button)$/i,d=/^[238]$/,p=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,f=/^(?:checked|selected)$/i;a(e,"attrFn",o||{},"jQuery.attrFn is deprecated"),e.attr=function(t,a,i,u){var c=a.toLowerCase(),g=t&&t.nodeType;return u&&(4>s.length&&r("jQuery.fn.attr( props, pass ) is deprecated"),t&&!d.test(g)&&(o?a in o:e.isFunction(e.fn[a])))?e(t)[a](i):("type"===a&&i!==n&&l.test(t.nodeName)&&t.parentNode&&r("Can't change the 'type' of an input or button in IE 6/7/8"),!e.attrHooks[c]&&p.test(c)&&(e.attrHooks[c]={get:function(t,r){var a,i=e.prop(t,r);return i===!0||"boolean"!=typeof i&&(a=t.getAttributeNode(r))&&a.nodeValue!==!1?r.toLowerCase():n},set:function(t,n,r){var a;return n===!1?e.removeAttr(t,r):(a=e.propFix[r]||r,a in t&&(t[a]=!0),t.setAttribute(r,r.toLowerCase())),r}},f.test(c)&&r("jQuery.fn.attr('"+c+"') may use property instead of attribute")),s.call(e,t,a,i))},e.attrHooks.value={get:function(e,t){var n=(e.nodeName||"").toLowerCase();return"button"===n?u.apply(this,arguments):("input"!==n&&"option"!==n&&r("jQuery.fn.attr('value') no longer gets properties"),t in e?e.value:null)},set:function(e,t){var a=(e.nodeName||"").toLowerCase();return"button"===a?c.apply(this,arguments):("input"!==a&&"option"!==a&&r("jQuery.fn.attr('value', val) no longer sets properties"),e.value=t,n)}};var g,h,v=e.fn.init,m=e.parseJSON,y=/^([^<]*)(<[\w\W]+>)([^>]*)$/;e.fn.init=function(t,n,a){var i;return t&&"string"==typeof t&&!e.isPlainObject(n)&&(i=y.exec(e.trim(t)))&&i[0]&&("<"!==t.charAt(0)&&r("$(html) HTML strings must start with '<' character"),i[3]&&r("$(html) HTML text after last tag is ignored"),"#"===i[0].charAt(0)&&(r("HTML string cannot start with a '#' character"),e.error("JQMIGRATE: Invalid selector string (XSS)")),n&&n.context&&(n=n.context),e.parseHTML)?v.call(this,e.parseHTML(i[2],n,!0),n,a):v.apply(this,arguments)},e.fn.init.prototype=e.fn,e.parseJSON=function(e){return e||null===e?m.apply(this,arguments):(r("jQuery.parseJSON requires a valid JSON string"),null)},e.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||0>e.indexOf("compatible")&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e.browser||(g=e.uaMatch(navigator.userAgent),h={},g.browser&&(h[g.browser]=!0,h.version=g.version),h.chrome?h.webkit=!0:h.webkit&&(h.safari=!0),e.browser=h),a(e,"browser",e.browser,"jQuery.browser is deprecated"),e.sub=function(){function t(e,n){return new t.fn.init(e,n)}e.extend(!0,t,this),t.superclass=this,t.fn=t.prototype=this(),t.fn.constructor=t,t.sub=this.sub,t.fn.init=function(r,a){return a&&a instanceof e&&!(a instanceof t)&&(a=t(a)),e.fn.init.call(this,r,a,n)},t.fn.init.prototype=t.fn;var n=t(document);return r("jQuery.sub() is deprecated"),t},e.ajaxSetup({converters:{"text json":e.parseJSON}});var b=e.fn.data;e.fn.data=function(t){var a,i,o=this[0];return!o||"events"!==t||1!==arguments.length||(a=e.data(o,t),i=e._data(o,t),a!==n&&a!==i||i===n)?b.apply(this,arguments):(r("Use of jQuery.fn.data('events') is deprecated"),i)};var j=/\/(java|ecma)script/i,w=e.fn.andSelf||e.fn.addBack;e.fn.andSelf=function(){return r("jQuery.fn.andSelf() replaced by jQuery.fn.addBack()"),w.apply(this,arguments)},e.clean||(e.clean=function(t,a,i,o){a=a||document,a=!a.nodeType&&a[0]||a,a=a.ownerDocument||a,r("jQuery.clean() is deprecated");var s,u,c,l,d=[];if(e.merge(d,e.buildFragment(t,a).childNodes),i)for(c=function(e){return!e.type||j.test(e.type)?o?o.push(e.parentNode?e.parentNode.removeChild(e):e):i.appendChild(e):n},s=0;null!=(u=d[s]);s++)e.nodeName(u,"script")&&c(u)||(i.appendChild(u),u.getElementsByTagName!==n&&(l=e.grep(e.merge([],u.getElementsByTagName("script")),c),d.splice.apply(d,[s+1,0].concat(l)),s+=l.length));return d});var Q=e.event.add,x=e.event.remove,k=e.event.trigger,N=e.fn.toggle,T=e.fn.live,M=e.fn.die,S="ajaxStart|ajaxStop|ajaxSend|ajaxComplete|ajaxError|ajaxSuccess",C=RegExp("\\b(?:"+S+")\\b"),H=/(?:^|\s)hover(\.\S+|)\b/,A=function(t){return"string"!=typeof t||e.event.special.hover?t:(H.test(t)&&r("'hover' pseudo-event is deprecated, use 'mouseenter mouseleave'"),t&&t.replace(H,"mouseenter$1 mouseleave$1"))};e.event.props&&"attrChange"!==e.event.props[0]&&e.event.props.unshift("attrChange","attrName","relatedNode","srcElement"),e.event.dispatch&&a(e.event,"handle",e.event.dispatch,"jQuery.event.handle is undocumented and deprecated"),e.event.add=function(e,t,n,a,i){e!==document&&C.test(t)&&r("AJAX events should be attached to document: "+t),Q.call(this,e,A(t||""),n,a,i)},e.event.remove=function(e,t,n,r,a){x.call(this,e,A(t)||"",n,r,a)},e.fn.error=function(){var e=Array.prototype.slice.call(arguments,0);return r("jQuery.fn.error() is deprecated"),e.splice(0,0,"error"),arguments.length?this.bind.apply(this,e):(this.triggerHandler.apply(this,e),this)},e.fn.toggle=function(t,n){if(!e.isFunction(t)||!e.isFunction(n))return N.apply(this,arguments);r("jQuery.fn.toggle(handler, handler...) is deprecated");var a=arguments,i=t.guid||e.guid++,o=0,s=function(n){var r=(e._data(this,"lastToggle"+t.guid)||0)%o;return e._data(this,"lastToggle"+t.guid,r+1),n.preventDefault(),a[r].apply(this,arguments)||!1};for(s.guid=i;a.length>o;)a[o++].guid=i;return this.click(s)},e.fn.live=function(t,n,a){return r("jQuery.fn.live() is deprecated"),T?T.apply(this,arguments):(e(this.context).on(t,this.selector,n,a),this)},e.fn.die=function(t,n){return r("jQuery.fn.die() is deprecated"),M?M.apply(this,arguments):(e(this.context).off(t,this.selector||"**",n),this)},e.event.trigger=function(e,t,n,a){return n||C.test(e)||r("Global events are undocumented and deprecated"),k.call(this,e,t,n||document,a)},e.each(S.split("|"),function(t,n){e.event.special[n]={setup:function(){var t=this;return t!==document&&(e.event.add(document,n+"."+e.guid,function(){e.event.trigger(n,null,t,!0)}),e._data(this,n,e.guid++)),!1},teardown:function(){return this!==document&&e.event.remove(document,n+"."+e._data(this,n)),!1}}})}(jQuery,window);
src/components/Sidebar/Copyright/Copyright.js
apalhu/website
// @flow strict import React from 'react'; import styles from './Copyright.module.scss'; type Props = { copyright: string }; const Copyright = ({ copyright }: Props) => ( <div className={styles['copyright']}> {copyright} </div> ); export default Copyright;
app/javascript/mastodon/features/account_timeline/containers/header_container.js
rainyday/mastodon
import React from 'react'; import { connect } from 'react-redux'; import { makeGetAccount } from '../../../selectors'; import Header from '../components/header'; import { followAccount, unfollowAccount, unblockAccount, unmuteAccount, pinAccount, unpinAccount, } from '../../../actions/accounts'; import { mentionCompose, directCompose, } from '../../../actions/compose'; import { initMuteModal } from '../../../actions/mutes'; import { initBlockModal } from '../../../actions/blocks'; import { initReport } from '../../../actions/reports'; import { openModal } from '../../../actions/modal'; import { blockDomain, unblockDomain } from '../../../actions/domain_blocks'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import { unfollowModal } from '../../../initial_state'; import { List as ImmutableList } from 'immutable'; const messages = defineMessages({ unfollowConfirm: { id: 'confirmations.unfollow.confirm', defaultMessage: 'Unfollow' }, blockDomainConfirm: { id: 'confirmations.domain_block.confirm', defaultMessage: 'Hide entire domain' }, }); const makeMapStateToProps = () => { const getAccount = makeGetAccount(); const mapStateToProps = (state, { accountId }) => ({ account: getAccount(state, accountId), domain: state.getIn(['meta', 'domain']), identity_proofs: state.getIn(['identity_proofs', accountId], ImmutableList()), }); return mapStateToProps; }; const mapDispatchToProps = (dispatch, { intl }) => ({ onFollow (account) { if (account.getIn(['relationship', 'following']) || account.getIn(['relationship', 'requested'])) { if (unfollowModal) { dispatch(openModal('CONFIRM', { message: <FormattedMessage id='confirmations.unfollow.message' defaultMessage='Are you sure you want to unfollow {name}?' values={{ name: <strong>@{account.get('acct')}</strong> }} />, confirm: intl.formatMessage(messages.unfollowConfirm), onConfirm: () => dispatch(unfollowAccount(account.get('id'))), })); } else { dispatch(unfollowAccount(account.get('id'))); } } else { dispatch(followAccount(account.get('id'))); } }, onBlock (account) { if (account.getIn(['relationship', 'blocking'])) { dispatch(unblockAccount(account.get('id'))); } else { dispatch(initBlockModal(account)); } }, onMention (account, router) { dispatch(mentionCompose(account, router)); }, onDirect (account, router) { dispatch(directCompose(account, router)); }, onReblogToggle (account) { if (account.getIn(['relationship', 'showing_reblogs'])) { dispatch(followAccount(account.get('id'), false)); } else { dispatch(followAccount(account.get('id'), true)); } }, onEndorseToggle (account) { if (account.getIn(['relationship', 'endorsed'])) { dispatch(unpinAccount(account.get('id'))); } else { dispatch(pinAccount(account.get('id'))); } }, onReport (account) { dispatch(initReport(account)); }, onMute (account) { if (account.getIn(['relationship', 'muting'])) { dispatch(unmuteAccount(account.get('id'))); } else { dispatch(initMuteModal(account)); } }, onBlockDomain (domain) { dispatch(openModal('CONFIRM', { message: <FormattedMessage id='confirmations.domain_block.message' defaultMessage='Are you really, really sure you want to block the entire {domain}? In most cases a few targeted blocks or mutes are sufficient and preferable. You will not see content from that domain in any public timelines or your notifications. Your followers from that domain will be removed.' values={{ domain: <strong>{domain}</strong> }} />, confirm: intl.formatMessage(messages.blockDomainConfirm), onConfirm: () => dispatch(blockDomain(domain)), })); }, onUnblockDomain (domain) { dispatch(unblockDomain(domain)); }, onAddToList(account){ dispatch(openModal('LIST_ADDER', { accountId: account.get('id'), })); }, }); export default injectIntl(connect(makeMapStateToProps, mapDispatchToProps)(Header));
src/components/menu/modals/leaderboard.js
aautem/aa
import React from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import * as friendsActions from '../../../store/actions/friends'; import * as messagesActions from '../../../store/actions/messages'; import * as leaderboardActions from '../../../store/actions/leaderboard'; import { Dimensions, Modal, View, Text, Slider, Switch, ActivityIndicator, TouchableOpacity, TouchableHighlight, Picker, ScrollView } from 'react-native'; import { Grid, Col, Row } from 'react-native-easy-grid'; import { Button, Avatar, SearchBar, List, ListItem } from 'react-native-elements'; import { ColorPicker } from 'react-native-color-picker' const modalSS = require('../../../styles/modals'); const appSS = require('../../../styles/app'); const { width: viewportWidth, height: viewportHeight } = Dimensions.get('window'); const data = [ { username: 'test', avatarUrl: 'https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/15380534_10211229273906159_7083414066462096595_n.jpg?oh=9eeef6cf9e9c6b64d68b44597627d88d&oe=5A9ED3B6', stats: { wins: 4, gamesPlayed: 13, totalPoints: 367 }, settings: { color: 'steelblue' }}, { username: 'test', avatarUrl: 'https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/15380534_10211229273906159_7083414066462096595_n.jpg?oh=9eeef6cf9e9c6b64d68b44597627d88d&oe=5A9ED3B6', stats: { wins: 4, gamesPlayed: 13, totalPoints: 367 }, settings: { color: 'steelblue' }}, { username: 'test', avatarUrl: 'https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/15380534_10211229273906159_7083414066462096595_n.jpg?oh=9eeef6cf9e9c6b64d68b44597627d88d&oe=5A9ED3B6', stats: { wins: 4, gamesPlayed: 13, totalPoints: 367 }, settings: { color: 'steelblue' }}, { username: 'test', avatarUrl: 'https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/15380534_10211229273906159_7083414066462096595_n.jpg?oh=9eeef6cf9e9c6b64d68b44597627d88d&oe=5A9ED3B6', stats: { wins: 4, gamesPlayed: 13, totalPoints: 367 }, settings: { color: 'steelblue' }}, { username: 'test', avatarUrl: 'https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/15380534_10211229273906159_7083414066462096595_n.jpg?oh=9eeef6cf9e9c6b64d68b44597627d88d&oe=5A9ED3B6', stats: { wins: 4, gamesPlayed: 13, totalPoints: 367 }, settings: { color: 'steelblue' }}, { username: 'test', avatarUrl: 'https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/15380534_10211229273906159_7083414066462096595_n.jpg?oh=9eeef6cf9e9c6b64d68b44597627d88d&oe=5A9ED3B6', stats: { wins: 4, gamesPlayed: 13, totalPoints: 367 }, settings: { color: 'steelblue' }}, { username: 'test', avatarUrl: 'https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/15380534_10211229273906159_7083414066462096595_n.jpg?oh=9eeef6cf9e9c6b64d68b44597627d88d&oe=5A9ED3B6', stats: { wins: 4, gamesPlayed: 13, totalPoints: 367 }, settings: { color: 'steelblue' }}, { username: 'test', avatarUrl: 'https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/15380534_10211229273906159_7083414066462096595_n.jpg?oh=9eeef6cf9e9c6b64d68b44597627d88d&oe=5A9ED3B6', stats: { wins: 4, gamesPlayed: 13, totalPoints: 367 }, settings: { color: 'steelblue' }}, { username: 'test', avatarUrl: 'https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/15380534_10211229273906159_7083414066462096595_n.jpg?oh=9eeef6cf9e9c6b64d68b44597627d88d&oe=5A9ED3B6', stats: { wins: 4, gamesPlayed: 13, totalPoints: 367 }, settings: { color: 'steelblue' }}, { username: 'test', avatarUrl: 'https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/15380534_10211229273906159_7083414066462096595_n.jpg?oh=9eeef6cf9e9c6b64d68b44597627d88d&oe=5A9ED3B6', stats: { wins: 4, gamesPlayed: 13, totalPoints: 367 }, settings: { color: 'steelblue' }}, { username: 'test', avatarUrl: 'https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/15380534_10211229273906159_7083414066462096595_n.jpg?oh=9eeef6cf9e9c6b64d68b44597627d88d&oe=5A9ED3B6', stats: { wins: 4, gamesPlayed: 13, totalPoints: 367 }, settings: { color: 'steelblue' }}, { username: 'test', avatarUrl: 'https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/15380534_10211229273906159_7083414066462096595_n.jpg?oh=9eeef6cf9e9c6b64d68b44597627d88d&oe=5A9ED3B6', stats: { wins: 4, gamesPlayed: 13, totalPoints: 367 }, settings: { color: 'steelblue' }}, { username: 'test', avatarUrl: 'https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/15380534_10211229273906159_7083414066462096595_n.jpg?oh=9eeef6cf9e9c6b64d68b44597627d88d&oe=5A9ED3B6', stats: { wins: 4, gamesPlayed: 13, totalPoints: 367 }, settings: { color: 'steelblue' }}, { username: 'test', avatarUrl: 'https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/15380534_10211229273906159_7083414066462096595_n.jpg?oh=9eeef6cf9e9c6b64d68b44597627d88d&oe=5A9ED3B6', stats: { wins: 4, gamesPlayed: 13, totalPoints: 367 }, settings: { color: 'steelblue' }}, { username: 'test', avatarUrl: 'https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/15380534_10211229273906159_7083414066462096595_n.jpg?oh=9eeef6cf9e9c6b64d68b44597627d88d&oe=5A9ED3B6', stats: { wins: 4, gamesPlayed: 13, totalPoints: 367 }, settings: { color: 'steelblue' }}, { username: 'test', avatarUrl: 'https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/15380534_10211229273906159_7083414066462096595_n.jpg?oh=9eeef6cf9e9c6b64d68b44597627d88d&oe=5A9ED3B6', stats: { wins: 4, gamesPlayed: 13, totalPoints: 367 }, settings: { color: 'steelblue' }}, { username: 'test', avatarUrl: 'https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/15380534_10211229273906159_7083414066462096595_n.jpg?oh=9eeef6cf9e9c6b64d68b44597627d88d&oe=5A9ED3B6', stats: { wins: 4, gamesPlayed: 13, totalPoints: 367 }, settings: { color: 'steelblue' }}, { username: 'test', avatarUrl: 'https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/15380534_10211229273906159_7083414066462096595_n.jpg?oh=9eeef6cf9e9c6b64d68b44597627d88d&oe=5A9ED3B6', stats: { wins: 4, gamesPlayed: 13, totalPoints: 367 }, settings: { color: 'steelblue' }}, { username: 'test', avatarUrl: 'https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/15380534_10211229273906159_7083414066462096595_n.jpg?oh=9eeef6cf9e9c6b64d68b44597627d88d&oe=5A9ED3B6', stats: { wins: 4, gamesPlayed: 13, totalPoints: 367 }, settings: { color: 'steelblue' }}, { username: 'test', avatarUrl: 'https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/15380534_10211229273906159_7083414066462096595_n.jpg?oh=9eeef6cf9e9c6b64d68b44597627d88d&oe=5A9ED3B6', stats: { wins: 4, gamesPlayed: 13, totalPoints: 367 }, settings: { color: 'steelblue' }}, ]; function mapStateToProps(state) { return { leaderboard: state.leaderboard.data, showModal: state.leaderboard.showLeaderboardModal, loading: state.leaderboard.loading, loaded: state.leaderboard.loaded, error: state.leaderboard.error, }; }; function mapDispatchToProps(dispatch) { return bindActionCreators({ closeLeaderboardModal: leaderboardActions.closeLeaderboardModal, }, dispatch); }; class LeaderboardModal extends React.Component { constructor(props) { super(props); } render() { return ( <Modal animationType='fade' visible={this.props.showModal} onRequestClose={this.props.closeLeaderboardModal} > {this.props.loading && <Col size={14/14} style={[appSS.center, { backgroundColor: '#aaa' }]}> <ActivityIndicator animating={true} color='#322893' size='large' /> <Text style={{ color: '#fff' }}>Loading</Text> </Col>} {!this.props.loading && <Col size={14/14}> {/* HEADER */} <Row size={2/24} style={{ justifyContent: 'center', alignItems: 'center', backgroundColor: '#eee', borderBottomWidth: 1, borderColor: '#aaa' }}> <Text style={{ fontWeight: 'bold', fontSize: 16, color: 'black' }}>Leaderboard</Text> </Row> <Row size={19/24}> <Col size={14/14}> <ScrollView> <List containerStyle={{ paddingLeft: 5, paddingRight: 5, marginTop: 0 }}> {this.props.leaderboard.map((player, i) => { console.log('Player:', player); return ( <ListItem roundAvatar hideChevron={true} avatar={{uri:player.avatarUrl}} key={i} title={player.username.toUpperCase()} titleStyle={{ color: 'black', fontWeight: 'bold' }} subtitle={`${player.stats.gamesPlayed} Games | ${player.stats.wins} Wins | ${player.stats.totalPoints} Points`} badge={{ value: `${((player.stats.wins / player.stats.gamesPlayed) * 100).toFixed(1)}% W`, textStyle: { color: '#fff', fontWeight: 'bold' }, containerStyle: { paddingTop: 5, paddingBottom: 5, backgroundColor: player.settings.color } }} /> ); })} </List> </ScrollView> </Col> </Row> {/* BUTTONS */} <Row size={3/24} style={{ justifyContent: 'center', alignItems: 'center', width: '100%', backgroundColor: '#eee', borderTopWidth: 2, borderColor: '#aaa' }}> <Button title='Main Menu' backgroundColor='#ccc' borderRadius={5} buttonStyle={{ width: '100%', borderWidth: 1, borderColor: '#aaa', width: 150 }} textStyle={{ color: 'black', fontWeight: 'bold' }} onPress={this.props.closeLeaderboardModal} /> </Row> </Col>} </Modal> ); } } LeaderboardModal.propTypes = { showModal: PropTypes.bool, closeLeaderboardModal: PropTypes.func, loading: PropTypes.bool, loaded: PropTypes.bool, error: PropTypes.string, }; export default connect(mapStateToProps, mapDispatchToProps)(LeaderboardModal);
viasat/sites/all/modules/jquery_update/replace/jquery/1.9/jquery.js
abbygailbndct/kurrent
/*! * jQuery JavaScript Library v1.9.1 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-2-4 */ (function( window, undefined ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ //"use strict"; var // The deferred used on DOM ready readyList, // A central reference to the root jQuery(document) rootjQuery, // Support: IE<9 // For `typeof node.method` instead of `node.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) document = window.document, location = window.location, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "1.9.1", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }, // The ready event handler completed = function( event ) { // readyState === "complete" is good enough for us to call the dom ready in oldIE if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { detach(); jQuery.ready(); } }, // Clean-up method for dom ready events detach = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } if ( data === null ) { return data; } if ( typeof data === "string" ) { // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); if ( data ) { // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } } } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && jQuery.trim( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { core_push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var args, proxy, tmp; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", completed ); // A fallback to window.onload, that will always work window.attachEvent( "onload", completed ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // First callback to fire (used internally by add and fireWith) firingStart, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( list && ( !fired || stack ) ) { if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function() { var support, all, a, input, select, fragment, opt, eventName, isSupported, i, div = document.createElement("div"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Support tests won't run in some limited or non-browser environments all = div.getElementsByTagName("*"); a = div.getElementsByTagName("a")[ 0 ]; if ( !all || !a || !all.length ) { return {}; } // First batch of tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; support = { // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // IE strips leading whitespace when .innerHTML is used leadingWhitespace: div.firstChild.nodeType === 3, // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: a.getAttribute("href") === "/a", // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.5/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) checkOn: !!input.value, // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Tests for enctype support on a form (#6743) enctype: !!document.createElement("form").enctype, // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode boxModel: document.compatMode === "CSS1Compat", // Will be defined later deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true, boxSizingReliable: true, pixelPosition: false }; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE<9 try { delete div.test; } catch( e ) { support.deleteExpando = false; } // Check if we can trust getAttribute("value") input = document.createElement("input"); input.setAttribute( "value", "" ); support.input = input.getAttribute( "value" ) === ""; // Check if an input maintains its value after becoming a radio input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment = document.createDocumentFragment(); fragment.appendChild( input ); // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<9 // Opera does not clone events (and typeof div.attachEvent === undefined). // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() if ( div.attachEvent ) { div.attachEvent( "onclick", function() { support.noCloneEvent = false; }); div.cloneNode( true ).click(); } // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP), test/csp.php for ( i in { submit: true, change: true, focusin: true }) { div.setAttribute( eventName = "on" + i, "t" ); support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; } div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, tds, divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; body.appendChild( container ).appendChild( div ); // Support: IE8 // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Support: IE8 // Check if empty table cells still have offsetWidth/Height support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check box-sizing and margin behavior div.innerHTML = ""; div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; support.boxSizing = ( div.offsetWidth === 4 ); support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement("div") ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== core_strundefined ) { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Support: IE6 // Check if elements with layout shrink-wrap their children div.style.display = "block"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); if ( support.inlineBlockNeedsLayout ) { // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 // Support: IE<8 body.style.zoom = 1; } } body.removeChild( container ); // Null elements to avoid leaks in IE container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE all = select = fragment = opt = a = input = null; return support; })(); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function internalData( elem, name, data, pvt /* Internal Use Only */ ){ if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { elem[ internalKey ] = id = core_deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { cache[ id ] = {}; // Avoids exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( getByName ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; } function internalRemoveData( elem, name, pvt ) { if ( !jQuery.acceptData( elem ) ) { return; } var i, l, thisCache, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } else { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = name.concat( jQuery.map( name, jQuery.camelCase ) ); } for ( i = 0, l = name.length; i < l; i++ ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) } else if ( jQuery.support.deleteExpando || cache != cache.window ) { delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } } jQuery.extend({ cache: {}, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data ) { return internalData( elem, name, data ); }, removeData: function( elem, name ) { return internalRemoveData( elem, name ); }, // For internal use only. _data: function( elem, name, data ) { return internalData( elem, name, data, true ); }, _removeData: function( elem, name ) { return internalRemoveData( elem, name, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { // Do not set data on non-element because it will not be cleared (#8335). if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) { return false; } var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function( key, value ) { var attrs, name, elem = this[0], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; i++ ) { name = attrs[i].name; if ( !name.indexOf( "data-" ) ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } return jQuery.access( this, function( value ) { if ( value === undefined ) { // Try to fetch any internally stored data first return elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null; } this.each(function() { jQuery.data( this, key, value ); }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } hooks.cur = fn; if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery._removeData( elem, type + "queue" ); jQuery._removeData( elem, key ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, rclass = /[\t\r\n]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i, rboolean = /^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, getSetInput = jQuery.support.input; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.match( core_rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } // Toggle whole class name } else if ( type === core_strundefined || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var ret, hooks, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val, self = jQuery(this); if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, attr: function( elem, name, value ) { var hooks, notxml, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === core_strundefined ) { return jQuery.prop( elem, name, value ); } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // All attributes are lowercase // Grab necessary hook if one is defined if ( notxml ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && notxml && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && notxml && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { // In IE9+, Flash objects don't have .getAttribute (#12945) // Support: IE9+ if ( typeof elem.getAttribute !== core_strundefined ) { ret = elem.getAttribute( name ); } // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( core_rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( rboolean.test( name ) ) { // Set corresponding property to false for boolean attributes // Also clear defaultChecked/defaultSelected (if appropriate) for IE<8 if ( !getSetAttribute && ruseDefault.test( name ) ) { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ propName ] = false; } else { elem[ propName ] = false; } // See #9699 for explanation of this approach (setting first, then removal) } else { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, propFix: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { return ( elem[ name ] = value ); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { return elem[ name ]; } } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ var attributeNode = elem.getAttributeNode("tabindex"); return attributeNode && attributeNode.specified ? parseInt( attributeNode.value, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } } } }); // Hook for boolean attributes boolHook = { get: function( elem, name ) { var // Use .prop to determine if this attribute is understood as boolean prop = jQuery.prop( elem, name ), // Fetch it accordingly attr = typeof prop === "boolean" && elem.getAttribute( name ), detail = typeof prop === "boolean" ? getSetInput && getSetAttribute ? attr != null : // oldIE fabricates an empty string for missing boolean attributes // and conflates checked/selected into attroperties ruseDefault.test( name ) ? elem[ jQuery.camelCase( "default-" + name ) ] : !!attr : // fetch an attribute node for properties not recognized as boolean elem.getAttributeNode( name ); return detail && detail.value !== false ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { // IE<8 needs the *property* name elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); // Use defaultChecked and defaultSelected for oldIE } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; } return name; } }; // fix oldIE value attroperty if ( !getSetInput || !getSetAttribute ) { jQuery.attrHooks.value = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return jQuery.nodeName( elem, "input" ) ? // Ignore the value *property* by using defaultValue elem.defaultValue : ret && ret.specified ? ret.value : undefined; }, set: function( elem, value, name ) { if ( jQuery.nodeName( elem, "input" ) ) { // Does not return so that setAttribute is also used elem.defaultValue = value; } else { // Use nodeHook if defined (#1954); otherwise setAttribute is fine return nodeHook && nodeHook.set( elem, value, name ); } } }; } // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return ret && ( name === "id" || name === "name" || name === "coords" ? ret.value !== "" : ret.specified ) ? ret.value : undefined; }, set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { elem.setAttributeNode( (ret = elem.ownerDocument.createAttribute( name )) ); } ret.value = value += ""; // Break association with cloned elements by also using setAttribute (#9646) return name === "value" || value === elem.getAttribute( name ) ? value : undefined; } }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { get: nodeHook.get, set: function( elem, value, name ) { nodeHook.set( elem, value === "" ? false : value, name ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }); }); } // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !jQuery.support.hrefNormalized ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret == null ? undefined : ret; } }); }); // href/src property should get the full normalized URL (#10299/#12915) jQuery.each([ "href", "src" ], function( i, name ) { jQuery.propHooks[ name ] = { get: function( elem ) { return elem.getAttribute( name, 4 ); } }; }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Note: IE uppercases css property names, but if we were to .toLowerCase() // .cssText, that would destroy case senstitivity in URL's, like in "background" return elem.style.cssText || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }); } // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { get: function( elem ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }); }); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var tmp, events, t, handleObjIn, special, eventHandle, handleObj, handlers, type, namespaces, origType, elemData = jQuery._data( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, handleObj, tmp, origCount, t, events, special, handlers, type, namespaces, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery._removeData( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var handle, ontype, cur, bubbleType, special, tmp, i, eventPath = [ elem || document ], type = core_hasOwn.call( event, "type" ) ? event.type : event, namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); event.isTrigger = true; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; try { elem[ type ](); } catch ( e ) { // IE<9 dies on focus/blur to hidden element (#1486,#12518) // only reproducible on winXP IE8 native, not IE9 in IE8 mode } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, ret, handleObj, matched, j, handlerQueue = [], args = core_slice.call( arguments ), handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var sel, handleObj, matches, i, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { for ( ; cur != this; cur = cur.parentNode || this ) { // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: IE<9 // Fix target property (#1925) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Support: Chrome 23+, Safari? // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Support: IE<9 // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) event.metaKey = !!event.metaKey; return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var body, eventDoc, doc, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { this.click(); return false; } } }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== document.activeElement && this.focus ) { try { this.focus(); return false; } catch ( e ) { // Support: IE<9 // If we error on focus to hidden element (#1486, #12518), // let .trigger() run the handlers } } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === document.activeElement && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, beforeunload: { postDispatch: function( event ) { // Even when returnValue equals to undefined Firefox will still show alert if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === core_strundefined ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( !e ) { return; } // If preventDefault exists, run it on the original event if ( e.preventDefault ) { e.preventDefault(); // Support: IE // Otherwise set the returnValue property of the original event to false } else { e.returnValue = false; } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( !e ) { return; } // If stopPropagation exists, run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // Support: IE // Set the cancelBubble property of the original event to true e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "submitBubbles" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "submitBubbles", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "changeBubbles", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var type, origFn; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); /*! * Sizzle CSS Selector Engine * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://sizzlejs.com/ */ (function( window, undefined ) { var i, cachedruns, Expr, getText, isXML, compile, hasDuplicate, outermostContext, // Local document vars setDocument, document, docElem, documentIsXML, rbuggyQSA, rbuggyMatches, matches, contains, sortOrder, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, support = {}, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Array methods arr = [], pop = arr.pop, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors operators = "([*^$|!~]?=)", attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rsibling = /[\x20\t\r\n\f]*[+~]/, rnative = /^[^{]+\{\s*\[native code/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rescape = /'|\\/g, rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g, funescape = function( _, escaped ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint return high !== high ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Use a stripped-down slice if we can't use a native one try { slice.call( preferredDoc.documentElement.childNodes, 0 )[0].nodeType; } catch ( e ) { slice = function( i ) { var elem, results = []; while ( (elem = this[i++]) ) { results.push( elem ); } return results; }; } /** * For feature detection * @param {Function} fn The function to test for native support */ function isNative( fn ) { return rnative.test( fn + "" ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var cache, keys = []; return (cache = function( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key += " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key ] = value); }); } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return fn( div ); } catch (e) { return false; } finally { // release memory in IE div = null; } } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( !documentIsXML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getByClassName && context.getElementsByClassName ) { push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); return results; } } // QSA path if ( support.qsa && !rbuggyQSA.test(selector) ) { old = true; nid = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, slice.call( newContext.querySelectorAll( newSelector ), 0 ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Detect xml * @param {Element|Object} elem An element or a document */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var doc = node ? node.ownerDocument || node : preferredDoc; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsXML = isXML( doc ); // Check if getElementsByTagName("*") returns only elements support.tagNameNoComments = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if attributes should be retrieved by attribute nodes support.attributes = assert(function( div ) { div.innerHTML = "<select></select>"; var type = typeof div.lastChild.getAttribute("multiple"); // IE8 returns a string for some attributes even when not present return type !== "boolean" && type !== "string"; }); // Check if getElementsByClassName can be trusted support.getByClassName = assert(function( div ) { // Opera can't find a second classname (in 9.6) div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>"; if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) { return false; } // Safari 3.2 caches class attributes and doesn't catch changes div.lastChild.className = "e"; return div.getElementsByClassName("e").length === 2; }); // Check if getElementById returns elements by name // Check if getElementsByName privileges form controls or returns elements by ID support.getByName = assert(function( div ) { // Inject content div.id = expando + 0; div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>"; docElem.insertBefore( div, docElem.firstChild ); // Test var pass = doc.getElementsByName && // buggy browsers will return fewer than the correct 2 doc.getElementsByName( expando ).length === 2 + // buggy browsers will return more than the correct 0 doc.getElementsByName( expando + 0 ).length; support.getIdNotName = !doc.getElementById( expando ); // Cleanup docElem.removeChild( div ); return pass; }); // IE6/7 return modified attributes Expr.attrHandle = assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && div.firstChild.getAttribute("href") === "#"; }) ? {} : { "href": function( elem ) { return elem.getAttribute( "href", 2 ); }, "type": function( elem ) { return elem.getAttribute("type"); } }; // ID find and filter if ( support.getIdNotName ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && !documentIsXML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && !documentIsXML ) { var m = context.getElementById( id ); return m ? m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? [m] : undefined : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.tagNameNoComments ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Name Expr.find["NAME"] = support.getByName && function( tag, context ) { if ( typeof context.getElementsByName !== strundefined ) { return context.getElementsByName( name ); } }; // Class Expr.find["CLASS"] = support.getByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && !documentIsXML ) { return context.getElementsByClassName( className ); } }; // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21), // no need to also add to buggyMatches since matches checks buggyQSA // A support test would require too much code (would include document ready) rbuggyQSA = [ ":focus" ]; if ( (support.qsa = isNative(doc.querySelectorAll)) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explictly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // IE8 - Some boolean attributes are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Opera 10-12/IE8 - ^= $= *= and empty values // Should not select anything div.innerHTML = "<input type='hidden' i=''/>"; if ( div.querySelectorAll("[i^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = isNative( (matches = docElem.matchesSelector || docElem.mozMatchesSelector || docElem.webkitMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = new RegExp( rbuggyMatches.join("|") ); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = isNative(docElem.contains) || docElem.compareDocumentPosition ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; // Document order sorting sortOrder = docElem.compareDocumentPosition ? function( a, b ) { var compare; if ( a === b ) { hasDuplicate = true; return 0; } if ( (compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b )) ) { if ( compare & 1 || a.parentNode && a.parentNode.nodeType === 11 ) { if ( a === doc || contains( preferredDoc, a ) ) { return -1; } if ( b === doc || contains( preferredDoc, b ) ) { return 1; } return 0; } return compare & 4 ? -1 : 1; } return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; // Always assume the presence of duplicates if sort doesn't // pass them to our comparison function (as in Google Chrome). hasDuplicate = false; [0, 0].sort( sortOrder ); support.detectDuplicates = hasDuplicate; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); // rbuggyQSA always contains :focus, so no need for an existence check if ( support.matchesSelector && !documentIsXML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !rbuggyQSA.test(expr) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { var val; // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } if ( !documentIsXML ) { name = name.toLowerCase(); } if ( (val = Expr.attrHandle[ name ]) ) { return val( elem ); } if ( documentIsXML || support.attributes ) { return elem.getAttribute( name ); } return ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ? name : val && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; // Document sorting and removing duplicates Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], i = 1, j = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; results.sort( sortOrder ); if ( hasDuplicate ) { for ( ; (elem = results[i]); i++ ) { if ( elem === results[ i - 1 ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; function siblingCheck( a, b ) { var cur = b && a, diff = cur && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } // Returns a function to use in pseudos for input types function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } // Returns a function to use in pseudos for buttons function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } // Returns a function to use in pseudos for positionals function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[4] ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeName ) { if ( nodeName === "*" ) { return function() { return true; }; } nodeName = nodeName.replace( runescape, funescape ).toLowerCase(); return function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifider if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsXML ? elem.getAttribute("xml:lang") || elem.getAttribute("lang") : elem.lang) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push( { value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) } ); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push( { value: matched, type: type, matches: match } ); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var data, cache, outerCache, dirkey = dirruns + " " + doneName; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( tokens.slice( 0, i - 1 ) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++matcherCachedRuns; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && !documentIsXML && Expr.relative[ tokens[1].type ] ) { context = Expr.find["ID"]( token.matches[0].replace( runescape, funescape ), context )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && context.parentNode || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, slice.call( seed, 0 ) ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, documentIsXML, results, rsibling.test( selector ) ); return results; } // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Easy API for creating new setFilters function setFilters() {} Expr.filters = setFilters.prototype = Expr.pseudos; Expr.setFilters = new setFilters(); // Initialize with the default document setDocument(); // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); var runtil = /Until$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, isSimple = /^.[^:#\[\.,]*$/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, ret, self, len = this.length; if ( typeof selector !== "string" ) { self = this; return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } ret = []; for ( i = 0; i < len; i++ ) { jQuery.find( selector, this[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = ( this.selector ? this.selector + " " : "" ) + selector; return ret; }, has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true) ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". rneedsContext.test( selector ) ? jQuery( selector, this.context ).index( this[0] ) >= 0 : jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { cur = this[i]; while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } cur = cur.parentNode; } } return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( jQuery.unique(all) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); jQuery.fn.andSelf = jQuery.fn.addBack; function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( this.length > 1 && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem ) { return ( elem === qualifier ) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, manipulation_rcheckableType = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], area: [ 1, "<map>", "</map>" ], param: [ 1, "<object>", "</object>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { return this.domManip( arguments, false, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, false, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length > 0 ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function( value ) { var isFunc = jQuery.isFunction( value ); // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( !isFunc && typeof value !== "string" ) { value = jQuery( value ).not( this ).detach(); } return this.domManip( [ value ], true, function( elem ) { var next = this.nextSibling, parent = this.parentNode; if ( parent ) { jQuery( this ).remove(); parent.insertBefore( elem, next ); } }); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { // Flatten any nested arrays args = core_concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, table ? self.html() : undefined ); } self.domManip( args, table, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( table && jQuery.nodeName( this[i], "table" ) ? findOrAppend( this[i], "tbody" ) : this[i], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Hope ajax is available... jQuery.ajax({ url: node.src, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); function findOrAppend( elem, tag ) { return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { var attr = elem.getAttributeNode("type"); elem.type = ( attr && attr.specified ) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( manipulation_rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while ( j-- ) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( typeof elem.removeAttribute !== core_strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } core_deletedIds.push( id ); } } } } } }); var iframe, getStyles, curCSS, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, rposition = /^(top|right|bottom|left)$/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { var len, styles, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { var bool = typeof state === "boolean"; return this.each(function() { if ( bool ? state : isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Exclude the following css properties to add px cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var num, val, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { getStyles = function( elem ) { return window.getComputedStyle( elem, null ); }; curCSS = function( elem, name, _computed ) { var width, minWidth, maxWidth, computed = _computed || getStyles( elem ), // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, style = elem.style; if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; } else if ( document.documentElement.currentStyle ) { getStyles = function( elem ) { return elem.currentStyle; }; curCSS = function( elem, name, _computed ) { var left, rs, rsLeft, computed = _computed || getStyles( elem ), ret = computed ? computed[ name ] : undefined, style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rs = elem.runtimeStyle; rsLeft = rs && rs.left; // Put in the new values to get a computed value out if ( rsLeft ) { rs.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { rs.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = ( iframe || jQuery("<iframe frameborder='0' width='0' height='0'/>") .css( "cssText", "display:block !important" ) ).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document; doc.write("<!doctype html><html><body>"); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } // Called ONLY from within css_defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), display = jQuery.css( elem[0], "display" ); elem.remove(); return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 // if value === "", then remove inline opacity #12685 if ( ( value >= 1 || value === "" ) && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there is no filter style applied in a css rule or unset inline opacity, we are done if ( value === "" || currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { if ( computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function(){ var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !manipulation_rcheckableType.test( type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.hover = function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }; var // Document location ajaxLocParts, ajaxLocation, ajax_nonce = jQuery.now(), ajax_rquery = /\?/, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[0] === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var deep, key, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, response, type, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){ jQuery.fn[ type ] = function( fn ){ return this.on( type, fn ); }; }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Cross-domain detection vars parts, // Loop variable i, // URL without anti-cache param cacheURL, // Response headers as string responseHeadersString, // timeout handle timeoutTimer, // To know if global events are to be dispatched fireGlobals, transport, // Response headers responseHeaders, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) : // Otherwise add one to the end cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 ) { isSuccess = true; statusText = "nocontent"; // if not modified } else if ( status === 304 ) { isSuccess = true; statusText = "notmodified"; // If we have data, let's convert it } else { isSuccess = ajaxConvert( s, response ); statusText = isSuccess.state; success = isSuccess.data; error = isSuccess.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); } }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var firstDataType, ct, finalDataType, type, contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields; // Fill responseXXX fields for ( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert( s, response ) { var conv2, current, conv, tmp, converters = {}, i = 0, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(), prev = dataTypes[ 0 ]; // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } // Convert to each sequential dataType, tolerating list modification for ( ; (current = dataTypes[++i]); ) { // There's only work to do if current dataType is non-auto if ( current !== "*" ) { // Convert response if prev dataType is non-auto and differs from current if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split(" "); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.splice( i--, 0, current ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s["throws"] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } // Update prev for next iteration prev = current; } } return { state: "success", data: response }; } // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || jQuery("head")[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement("script"); script.async = true; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( script.parentNode ) { script.parentNode.removeChild( script ); } // Dereference the script script = null; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending // Use native DOM manipulation to avoid our domManip AJAX trickery head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( undefined, true ); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); var xhrCallbacks, xhrSupported, xhrId = 0, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject && function() { // Abort all pending requests var key; for ( key in xhrCallbacks ) { xhrCallbacks[ key ]( undefined, true ); } }; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties xhrSupported = jQuery.ajaxSettings.xhr(); jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); xhrSupported = jQuery.support.ajax = !!xhrSupported; // Create transport if the browser can provide an xhr if ( xhrSupported ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( err ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, responseHeaders, statusText, responses; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { responses = {}; status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) if ( typeof xhr.responseText === "string" ) { responses.text = xhr.responseText; } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; if ( !s.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback ); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback( undefined, true ); } } }; } }); } var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function( prop, value ) { var end, unit, tween = this.createTween( prop, value ), parts = rfxnum.exec( value ), target = tween.cur(), start = +target || 0, scale = 1, maxIterations = 20; if ( parts ) { end = +parts[2]; unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" && start ) { // Iteratively approximate from a nonzero starting point // Prefer the current property, because this process will be trivial if it uses the same units // Fallback to end or a simple constant start = jQuery.css( tween.elem, prop, true ) || end || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } tween.unit = unit; tween.start = start; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } function createTweens( animation, props ) { jQuery.each( props, function( prop, value ) { var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( collection[ index ].call( animation, prop, value ) ) { // we're done with this property return; } } }); } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } createTweens( animation, props ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } function propFilter( props, specialEasing ) { var value, name, index, easing, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); function defaultPrefilter( elem, props, opts ) { /*jshint validthis:true */ var prop, index, length, value, dataShow, toggle, tween, hooks, oldfire, anim = this, style = elem.style, orig = {}, handled = [], hidden = elem.nodeType && isHidden( elem ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( elem, "display" ) === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !jQuery.support.shrinkWrapBlocks ) { anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( index in props ) { value = props[ index ]; if ( rfxtypes.exec( value ) ) { delete props[ index ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { continue; } handled.push( index ); } } length = handled.length; if ( length ) { dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} ); if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery._removeData( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( index = 0 ; index < length ; index++ ) { prop = handled[ index ]; tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 ); orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Remove in 2.0 - this supports IE8's panic based approach // to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); doAnimation.finish = function() { anim.stop( true ); }; // Empty animations, or finishing resolves immediately if ( empty || jQuery._data( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = jQuery._data( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // enable finishing flag on private data data.finish = true; // empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.cur && hooks.cur.finish ) { hooks.cur.finish.call( this ); } // look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // turn off finishing flag delete data.finish; }); } }); // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth? 1 : 0; for( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p*Math.PI ) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { if ( timer() && jQuery.timers.push( timer ) ) { jQuery.fx.start(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== core_strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ), left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 ) }; }; jQuery.offset = { setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, parentOffset = { top: 0, left: 0 }, elem = this[ 0 ]; // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // we assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.documentElement; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || document.documentElement; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return jQuery.access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // Limit scope pollution from any deprecated API // (function() { // })(); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; // Expose jQuery as an AMD module, but only for AMD loaders that // understand the issues with loading multiple versions of jQuery // in a page that all might call define(). The loader will indicate // they have special allowances for multiple jQuery versions by // specifying define.amd.jQuery = true. Register as a named module, // since jQuery can be concatenated with other files that may use define, // but not use a proper concatenation script that understands anonymous // AMD modules. A named AMD is safest and most robust way to register. // Lowercase jquery is used because AMD module names are derived from // file names, and jQuery is normally delivered in a lowercase file name. // Do this after creating the global so that if an AMD module wants to call // noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd && define.amd.jQuery ) { define( "jquery", [], function () { return jQuery; } ); } })( window );
packages/material-ui-icons/src/BackupTwoTone.js
allanalexandre/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M19.21 12.04l-1.53-.11-.3-1.5C16.88 7.86 14.62 6 12 6 9.94 6 8.08 7.14 7.12 8.96l-.5.95-1.07.11C3.53 10.24 2 11.95 2 14c0 2.21 1.79 4 4 4h13c1.65 0 3-1.35 3-3 0-1.55-1.22-2.86-2.79-2.96zm-5.76.96v3h-2.91v-3H8l4-4 4 4h-2.55z" opacity=".3" /><path d="M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM19 18H6c-2.21 0-4-1.79-4-4 0-2.05 1.53-3.76 3.56-3.97l1.07-.11.5-.95C8.08 7.14 9.94 6 12 6c2.62 0 4.88 1.86 5.39 4.43l.3 1.5 1.53.11c1.56.1 2.78 1.41 2.78 2.96 0 1.65-1.35 3-3 3z" /><path d="M8 13h2.55v3h2.9v-3H16l-4-4z" /></g></React.Fragment> , 'BackupTwoTone');
js/redux/learn-redux/node_modules/react-router/es6/RouteUtils.js
austinjalexander/sandbox
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'; function isValidChild(object) { return object == null || React.isValidElement(object); } export function isReactChildren(object) { return isValidChild(object) || Array.isArray(object) && object.every(isValidChild); } function createRoute(defaultProps, props) { return _extends({}, defaultProps, props); } export function createRouteFromReactElement(element) { var type = element.type; var route = createRoute(type.defaultProps, element.props); if (route.children) { var childRoutes = createRoutesFromReactChildren(route.children, route); if (childRoutes.length) route.childRoutes = childRoutes; delete route.children; } return route; } /** * Creates and returns a routes object from the given ReactChildren. JSX * provides a convenient way to visualize how routes in the hierarchy are * nested. * * import { Route, createRoutesFromReactChildren } from 'react-router' * * const routes = createRoutesFromReactChildren( * <Route component={App}> * <Route path="home" component={Dashboard}/> * <Route path="news" component={NewsFeed}/> * </Route> * ) * * Note: This method is automatically used when you provide <Route> children * to a <Router> component. */ export function createRoutesFromReactChildren(children, parentRoute) { var routes = []; React.Children.forEach(children, function (element) { if (React.isValidElement(element)) { // Component classes may have a static create* method. if (element.type.createRouteFromReactElement) { var route = element.type.createRouteFromReactElement(element, parentRoute); if (route) routes.push(route); } else { routes.push(createRouteFromReactElement(element)); } } }); return routes; } /** * Creates and returns an array of routes from the given object which * may be a JSX route, a plain object route, or an array of either. */ export function createRoutes(routes) { if (isReactChildren(routes)) { routes = createRoutesFromReactChildren(routes); } else if (routes && !Array.isArray(routes)) { routes = [routes]; } return routes; }
client/app/routes/main-routes.js
Raymond310/react-redux-sinatra-boilerplate
/** * Created by wliuhuiz on 9/13/15. */ import React from 'react' import {Router, Route} from 'react-router'; import MainApp from '../containers/MainApp' import Dashboard from "../containers/Dashboard" import Builds from "../containers/Builds" export default function renderRoutes (history) { return ( <Router history={history}> <Route path="/" component={MainApp} > <Route path="dashboard/?:q?" component={Dashboard} /> <Route path="builds" component={Builds} /> <Route path="*" component={Dashboard}/> </Route> </Router> ) }
lib/server.js
kodyl/react-document-meta
import DocumentMeta, { render } from './index'; import React from 'react'; import { renderToStaticMarkup } from 'react-dom/server'; function rewindAsStaticMarkup() { const tags = render(DocumentMeta.rewind()); return renderToStaticMarkup(<div>{tags}</div>) .replace(/(^<div>|<\/div>$)/g, '') .replace(/data-rdm="true"/g, 'data-rdm'); } export default DocumentMeta; DocumentMeta.renderToStaticMarkup = rewindAsStaticMarkup; DocumentMeta.renderAsHTML = rewindAsStaticMarkup;
src/svg-icons/image/filter-1.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFilter1 = (props) => ( <SvgIcon {...props}> <path d="M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm11 10h2V5h-4v2h2v8zm7-14H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14z"/> </SvgIcon> ); ImageFilter1 = pure(ImageFilter1); ImageFilter1.displayName = 'ImageFilter1'; ImageFilter1.muiName = 'SvgIcon'; export default ImageFilter1;
source/component/listview/newsRow.js
togayther/react-native-cnblogs
import React, { Component } from 'react'; import { View, Text, Image, TouchableHighlight } from 'react-native'; import _ from 'lodash'; import moment from 'moment'; import PureRenderMixin from 'react-addons-pure-render-mixin'; import { decodeHTML, getBloggerAvatar, getNewsUrlFromID } from '../../common'; import { ComponentStyles, CommonStyles, StyleConfig } from '../../style'; class NewsRow extends Component { constructor(props) { super(props); this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this); } getNewsInfo(){ let { news } = this.props; let newsInfo = {}; if (news && news.Id) { newsInfo.Id = news.Id; newsInfo.ViewCount = news.ViewCount; newsInfo.CommentCount = news.CommentCount; newsInfo.Title = decodeHTML(news.Title); if (news.Summary) { newsInfo.Description = _.truncate(decodeHTML(news.Summary), { length : 70 }); } newsInfo.Url = getNewsUrlFromID(news.Id); newsInfo.DateAdded = moment(news.DateAdded).startOf('minute').fromNow(); newsInfo.Avatar = getBloggerAvatar(news.TopicIcon); } return newsInfo; } renderNewsTitle(newsInfo){ return ( <View style={ [ CommonStyles.m_b_1 ] }> <Text style={ [CommonStyles.text_black, CommonStyles.font_sm, CommonStyles.line_height_md ] }> { newsInfo.Title } </Text> </View> ) } renderNewsDescr(newsInfo){ return ( <View style={ [ CommonStyles.m_b_2 ] }> <Text style={ [ CommonStyles.text_gray, CommonStyles.font_xs, CommonStyles.line_height_sm ] }> { newsInfo.Description } </Text> </View> ) } renderNewsMeta(newsInfo){ return ( <View style={ [ CommonStyles.flexRow, CommonStyles.flexItemsBetween ] }> <View style={[ CommonStyles.flexRow, CommonStyles.flexItemsMiddle ]}> <Image ref={ view => this.imgView=view } style={ [ ComponentStyles.avatar_mini, CommonStyles.m_r_2] } source={ newsInfo.Avatar }> </Image> <Text style={ [CommonStyles.text_gray, CommonStyles.font_ms] }> { newsInfo.DateAdded } </Text> </View> <View> <Text style={ [ CommonStyles.text_primary ] }> { newsInfo.CommentCount + ' / ' + newsInfo.ViewCount } </Text> </View> </View> ) } render() { const newsInfo = this.getNewsInfo(); return ( <TouchableHighlight onPress={(e)=>{ this.props.onRowPress(newsInfo) }} underlayColor={ StyleConfig.touchable_press_color } key={ newsInfo.Id }> <View style={ [ComponentStyles.list] }> { this.renderNewsTitle(newsInfo) } { this.renderNewsDescr(newsInfo) } { this.renderNewsMeta(newsInfo) } </View> </TouchableHighlight> ) } } export default NewsRow;
app/javascript/flavours/glitch/features/standalone/public_timeline/index.js
Kirishima21/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { expandPublicTimeline, expandCommunityTimeline } from 'flavours/glitch/actions/timelines'; import Masonry from 'react-masonry-infinite'; import { List as ImmutableList, Map as ImmutableMap } from 'immutable'; import DetailedStatusContainer from 'flavours/glitch/features/status/containers/detailed_status_container'; import { debounce } from 'lodash'; import LoadingIndicator from 'flavours/glitch/components/loading_indicator'; const mapStateToProps = (state, { local }) => { const timeline = state.getIn(['timelines', local ? 'community' : 'public'], ImmutableMap()); return { statusIds: timeline.get('items', ImmutableList()), isLoading: timeline.get('isLoading', false), hasMore: timeline.get('hasMore', false), }; }; export default @connect(mapStateToProps) class PublicTimeline extends React.PureComponent { static propTypes = { dispatch: PropTypes.func.isRequired, statusIds: ImmutablePropTypes.list.isRequired, isLoading: PropTypes.bool.isRequired, hasMore: PropTypes.bool.isRequired, local: PropTypes.bool, }; componentDidMount () { this._connect(); } componentDidUpdate (prevProps) { if (prevProps.local !== this.props.local) { this._disconnect(); this._connect(); } } _connect () { const { dispatch, local } = this.props; dispatch(local ? expandCommunityTimeline() : expandPublicTimeline()); } handleLoadMore = () => { const { dispatch, statusIds, local } = this.props; const maxId = statusIds.last(); if (maxId) { dispatch(local ? expandCommunityTimeline({ maxId }) : expandPublicTimeline({ maxId })); } } setRef = c => { this.masonry = c; } handleHeightChange = debounce(() => { if (!this.masonry) { return; } this.masonry.forcePack(); }, 50) render () { const { statusIds, hasMore, isLoading } = this.props; const sizes = [ { columns: 1, gutter: 0 }, { mq: '415px', columns: 1, gutter: 10 }, { mq: '640px', columns: 2, gutter: 10 }, { mq: '960px', columns: 3, gutter: 10 }, { mq: '1255px', columns: 3, gutter: 10 }, ]; const loader = (isLoading && statusIds.isEmpty()) ? <LoadingIndicator key={0} /> : undefined; return ( <Masonry ref={this.setRef} className='statuses-grid' hasMore={hasMore} loadMore={this.handleLoadMore} sizes={sizes} loader={loader}> {statusIds.map(statusId => ( <div className='statuses-grid__item' key={statusId}> <DetailedStatusContainer id={statusId} compact measureHeight onHeightChange={this.handleHeightChange} /> </div> )).toArray()} </Masonry> ); } }
ajax/libs/vis/3.2.0/vis.js
hare1039/cdnjs
/** * vis.js * https://github.com/almende/vis * * A dynamic, browser-based visualization library. * * @version 3.2.0 * @date 2014-08-14 * * @license * Copyright (C) 2011-2014 Almende B.V, http://almende.com * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define(factory); else if(typeof exports === 'object') exports["vis"] = factory(); else root["vis"] = factory(); })(this, function() { 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__) { // utils exports.util = __webpack_require__(1); exports.DOMutil = __webpack_require__(2); // data exports.DataSet = __webpack_require__(3); exports.DataView = __webpack_require__(4); // Graph3d exports.Graph3d = __webpack_require__(5); exports.graph3d = { Camera: __webpack_require__(6), Filter: __webpack_require__(7), Point2d: __webpack_require__(8), Point3d: __webpack_require__(9), Slider: __webpack_require__(10), StepNumber: __webpack_require__(11) }; // Timeline exports.Timeline = __webpack_require__(12); exports.Graph2d = __webpack_require__(13); exports.timeline = { DataStep: __webpack_require__(14), Range: __webpack_require__(15), stack: __webpack_require__(16), TimeStep: __webpack_require__(17), components: { items: { Item: __webpack_require__(29), ItemBox: __webpack_require__(28), ItemPoint: __webpack_require__(30), ItemRange: __webpack_require__(31) }, Component: __webpack_require__(18), CurrentTime: __webpack_require__(19), CustomTime: __webpack_require__(20), DataAxis: __webpack_require__(21), GraphGroup: __webpack_require__(22), Group: __webpack_require__(23), ItemSet: __webpack_require__(24), Legend: __webpack_require__(25), LineGraph: __webpack_require__(26), TimeAxis: __webpack_require__(27) } }; // Network exports.Network = __webpack_require__(32); exports.network = { Edge: __webpack_require__(33), Groups: __webpack_require__(34), Images: __webpack_require__(35), Node: __webpack_require__(36), Popup: __webpack_require__(37), dotparser: __webpack_require__(38), gephiParser: __webpack_require__(39) }; // Deprecated since v3.0.0 exports.Graph = function () { throw new Error('Graph is renamed to Network. Please create a graph as new vis.Network(...)'); }; // bundled external libraries exports.moment = __webpack_require__(40); exports.hammer = __webpack_require__(41); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { // utility functions // first check if moment.js is already loaded in the browser window, if so, // use this instance. Else, load via commonjs. var moment = __webpack_require__(40); /** * Test whether given object is a number * @param {*} object * @return {Boolean} isNumber */ exports.isNumber = function(object) { return (object instanceof Number || typeof object == 'number'); }; /** * Test whether given object is a string * @param {*} object * @return {Boolean} isString */ exports.isString = function(object) { return (object instanceof String || typeof object == 'string'); }; /** * Test whether given object is a Date, or a String containing a Date * @param {Date | String} object * @return {Boolean} isDate */ exports.isDate = function(object) { if (object instanceof Date) { return true; } else if (exports.isString(object)) { // test whether this string contains a date var match = ASPDateRegex.exec(object); if (match) { return true; } else if (!isNaN(Date.parse(object))) { return true; } } return false; }; /** * Test whether given object is an instance of google.visualization.DataTable * @param {*} object * @return {Boolean} isDataTable */ exports.isDataTable = function(object) { return (typeof (google) !== 'undefined') && (google.visualization) && (google.visualization.DataTable) && (object instanceof google.visualization.DataTable); }; /** * Create a semi UUID * source: http://stackoverflow.com/a/105074/1262753 * @return {String} uuid */ exports.randomUUID = function() { var S4 = function () { return Math.floor( Math.random() * 0x10000 /* 65536 */ ).toString(16); }; return ( S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4() ); }; /** * Extend object a with the properties of object b or a series of objects * Only properties with defined values are copied * @param {Object} a * @param {... Object} b * @return {Object} a */ exports.extend = function (a, b) { for (var i = 1, len = arguments.length; i < len; i++) { var other = arguments[i]; for (var prop in other) { if (other.hasOwnProperty(prop)) { a[prop] = other[prop]; } } } return a; }; /** * Extend object a with selected properties of object b or a series of objects * Only properties with defined values are copied * @param {Array.<String>} props * @param {Object} a * @param {... Object} b * @return {Object} a */ exports.selectiveExtend = function (props, a, b) { if (!Array.isArray(props)) { throw new Error('Array with property names expected as first argument'); } for (var i = 2; i < arguments.length; i++) { var other = arguments[i]; for (var p = 0; p < props.length; p++) { var prop = props[p]; if (other.hasOwnProperty(prop)) { a[prop] = other[prop]; } } } return a; }; /** * Extend object a with selected properties of object b or a series of objects * Only properties with defined values are copied * @param {Array.<String>} props * @param {Object} a * @param {... Object} b * @return {Object} a */ exports.selectiveDeepExtend = function (props, a, b) { // TODO: add support for Arrays to deepExtend if (Array.isArray(b)) { throw new TypeError('Arrays are not supported by deepExtend'); } for (var i = 2; i < arguments.length; i++) { var other = arguments[i]; for (var p = 0; p < props.length; p++) { var prop = props[p]; if (other.hasOwnProperty(prop)) { if (b[prop] && b[prop].constructor === Object) { if (a[prop] === undefined) { a[prop] = {}; } if (a[prop].constructor === Object) { exports.deepExtend(a[prop], b[prop]); } else { a[prop] = b[prop]; } } else if (Array.isArray(b[prop])) { throw new TypeError('Arrays are not supported by deepExtend'); } else { a[prop] = b[prop]; } } } } return a; }; /** * Extend object a with selected properties of object b or a series of objects * Only properties with defined values are copied * @param {Array.<String>} props * @param {Object} a * @param {... Object} b * @return {Object} a */ exports.selectiveNotDeepExtend = function (props, a, b) { // TODO: add support for Arrays to deepExtend if (Array.isArray(b)) { throw new TypeError('Arrays are not supported by deepExtend'); } for (var prop in b) { if (b.hasOwnProperty(prop)) { if (props.indexOf(prop) == -1) { if (b[prop] && b[prop].constructor === Object) { if (a[prop] === undefined) { a[prop] = {}; } if (a[prop].constructor === Object) { exports.deepExtend(a[prop], b[prop]); } else { a[prop] = b[prop]; } } else if (Array.isArray(b[prop])) { throw new TypeError('Arrays are not supported by deepExtend'); } else { a[prop] = b[prop]; } } } } return a; }; /** * Deep extend an object a with the properties of object b * @param {Object} a * @param {Object} b * @returns {Object} */ exports.deepExtend = function(a, b) { // TODO: add support for Arrays to deepExtend if (Array.isArray(b)) { throw new TypeError('Arrays are not supported by deepExtend'); } for (var prop in b) { if (b.hasOwnProperty(prop)) { if (b[prop] && b[prop].constructor === Object) { if (a[prop] === undefined) { a[prop] = {}; } if (a[prop].constructor === Object) { exports.deepExtend(a[prop], b[prop]); } else { a[prop] = b[prop]; } } else if (Array.isArray(b[prop])) { throw new TypeError('Arrays are not supported by deepExtend'); } else { a[prop] = b[prop]; } } } return a; }; /** * Test whether all elements in two arrays are equal. * @param {Array} a * @param {Array} b * @return {boolean} Returns true if both arrays have the same length and same * elements. */ exports.equalArray = function (a, b) { if (a.length != b.length) return false; for (var i = 0, len = a.length; i < len; i++) { if (a[i] != b[i]) return false; } return true; }; /** * Convert an object to another type * @param {Boolean | Number | String | Date | Moment | Null | undefined} object * @param {String | undefined} type Name of the type. Available types: * 'Boolean', 'Number', 'String', * 'Date', 'Moment', ISODate', 'ASPDate'. * @return {*} object * @throws Error */ exports.convert = function(object, type) { var match; if (object === undefined) { return undefined; } if (object === null) { return null; } if (!type) { return object; } if (!(typeof type === 'string') && !(type instanceof String)) { throw new Error('Type must be a string'); } //noinspection FallthroughInSwitchStatementJS switch (type) { case 'boolean': case 'Boolean': return Boolean(object); case 'number': case 'Number': return Number(object.valueOf()); case 'string': case 'String': return String(object); case 'Date': if (exports.isNumber(object)) { return new Date(object); } if (object instanceof Date) { return new Date(object.valueOf()); } else if (moment.isMoment(object)) { return new Date(object.valueOf()); } if (exports.isString(object)) { match = ASPDateRegex.exec(object); if (match) { // object is an ASP date return new Date(Number(match[1])); // parse number } else { return moment(object).toDate(); // parse string } } else { throw new Error( 'Cannot convert object of type ' + exports.getType(object) + ' to type Date'); } case 'Moment': if (exports.isNumber(object)) { return moment(object); } if (object instanceof Date) { return moment(object.valueOf()); } else if (moment.isMoment(object)) { return moment(object); } if (exports.isString(object)) { match = ASPDateRegex.exec(object); if (match) { // object is an ASP date return moment(Number(match[1])); // parse number } else { return moment(object); // parse string } } else { throw new Error( 'Cannot convert object of type ' + exports.getType(object) + ' to type Date'); } case 'ISODate': if (exports.isNumber(object)) { return new Date(object); } else if (object instanceof Date) { return object.toISOString(); } else if (moment.isMoment(object)) { return object.toDate().toISOString(); } else if (exports.isString(object)) { match = ASPDateRegex.exec(object); if (match) { // object is an ASP date return new Date(Number(match[1])).toISOString(); // parse number } else { return new Date(object).toISOString(); // parse string } } else { throw new Error( 'Cannot convert object of type ' + exports.getType(object) + ' to type ISODate'); } case 'ASPDate': if (exports.isNumber(object)) { return '/Date(' + object + ')/'; } else if (object instanceof Date) { return '/Date(' + object.valueOf() + ')/'; } else if (exports.isString(object)) { match = ASPDateRegex.exec(object); var value; if (match) { // object is an ASP date value = new Date(Number(match[1])).valueOf(); // parse number } else { value = new Date(object).valueOf(); // parse string } return '/Date(' + value + ')/'; } else { throw new Error( 'Cannot convert object of type ' + exports.getType(object) + ' to type ASPDate'); } default: throw new Error('Unknown type "' + type + '"'); } }; // parse ASP.Net Date pattern, // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/' // code from http://momentjs.com/ var ASPDateRegex = /^\/?Date\((\-?\d+)/i; /** * Get the type of an object, for example exports.getType([]) returns 'Array' * @param {*} object * @return {String} type */ exports.getType = function(object) { var type = typeof object; if (type == 'object') { if (object == null) { return 'null'; } if (object instanceof Boolean) { return 'Boolean'; } if (object instanceof Number) { return 'Number'; } if (object instanceof String) { return 'String'; } if (object instanceof Array) { return 'Array'; } if (object instanceof Date) { return 'Date'; } return 'Object'; } else if (type == 'number') { return 'Number'; } else if (type == 'boolean') { return 'Boolean'; } else if (type == 'string') { return 'String'; } return type; }; /** * Retrieve the absolute left value of a DOM element * @param {Element} elem A dom element, for example a div * @return {number} left The absolute left position of this element * in the browser page. */ exports.getAbsoluteLeft = function(elem) { return elem.getBoundingClientRect().left + window.pageXOffset; }; /** * Retrieve the absolute top value of a DOM element * @param {Element} elem A dom element, for example a div * @return {number} top The absolute top position of this element * in the browser page. */ exports.getAbsoluteTop = function(elem) { return elem.getBoundingClientRect().top + window.pageYOffset; }; /** * add a className to the given elements style * @param {Element} elem * @param {String} className */ exports.addClassName = function(elem, className) { var classes = elem.className.split(' '); if (classes.indexOf(className) == -1) { classes.push(className); // add the class to the array elem.className = classes.join(' '); } }; /** * add a className to the given elements style * @param {Element} elem * @param {String} className */ exports.removeClassName = function(elem, className) { var classes = elem.className.split(' '); var index = classes.indexOf(className); if (index != -1) { classes.splice(index, 1); // remove the class from the array elem.className = classes.join(' '); } }; /** * For each method for both arrays and objects. * In case of an array, the built-in Array.forEach() is applied. * In case of an Object, the method loops over all properties of the object. * @param {Object | Array} object An Object or Array * @param {function} callback Callback method, called for each item in * the object or array with three parameters: * callback(value, index, object) */ exports.forEach = function(object, callback) { var i, len; if (object instanceof Array) { // array for (i = 0, len = object.length; i < len; i++) { callback(object[i], i, object); } } else { // object for (i in object) { if (object.hasOwnProperty(i)) { callback(object[i], i, object); } } } }; /** * Convert an object into an array: all objects properties are put into the * array. The resulting array is unordered. * @param {Object} object * @param {Array} array */ exports.toArray = function(object) { var array = []; for (var prop in object) { if (object.hasOwnProperty(prop)) array.push(object[prop]); } return array; } /** * Update a property in an object * @param {Object} object * @param {String} key * @param {*} value * @return {Boolean} changed */ exports.updateProperty = function(object, key, value) { if (object[key] !== value) { object[key] = value; return true; } else { return false; } }; /** * Add and event listener. Works for all browsers * @param {Element} element An html element * @param {string} action The action, for example "click", * without the prefix "on" * @param {function} listener The callback function to be executed * @param {boolean} [useCapture] */ exports.addEventListener = function(element, action, listener, useCapture) { if (element.addEventListener) { if (useCapture === undefined) useCapture = false; if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) { action = "DOMMouseScroll"; // For Firefox } element.addEventListener(action, listener, useCapture); } else { element.attachEvent("on" + action, listener); // IE browsers } }; /** * Remove an event listener from an element * @param {Element} element An html dom element * @param {string} action The name of the event, for example "mousedown" * @param {function} listener The listener function * @param {boolean} [useCapture] */ exports.removeEventListener = function(element, action, listener, useCapture) { if (element.removeEventListener) { // non-IE browsers if (useCapture === undefined) useCapture = false; if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) { action = "DOMMouseScroll"; // For Firefox } element.removeEventListener(action, listener, useCapture); } else { // IE browsers element.detachEvent("on" + action, listener); } }; /** * Cancels the event if it is cancelable, without stopping further propagation of the event. */ exports.preventDefault = function (event) { if (!event) event = window.event; if (event.preventDefault) { event.preventDefault(); // non-IE browsers } else { event.returnValue = false; // IE browsers } }; /** * Get HTML element which is the target of the event * @param {Event} event * @return {Element} target element */ exports.getTarget = function(event) { // code from http://www.quirksmode.org/js/events_properties.html if (!event) { event = window.event; } var target; if (event.target) { target = event.target; } else if (event.srcElement) { target = event.srcElement; } if (target.nodeType != undefined && target.nodeType == 3) { // defeat Safari bug target = target.parentNode; } return target; }; exports.option = {}; /** * Convert a value into a boolean * @param {Boolean | function | undefined} value * @param {Boolean} [defaultValue] * @returns {Boolean} bool */ exports.option.asBoolean = function (value, defaultValue) { if (typeof value == 'function') { value = value(); } if (value != null) { return (value != false); } return defaultValue || null; }; /** * Convert a value into a number * @param {Boolean | function | undefined} value * @param {Number} [defaultValue] * @returns {Number} number */ exports.option.asNumber = function (value, defaultValue) { if (typeof value == 'function') { value = value(); } if (value != null) { return Number(value) || defaultValue || null; } return defaultValue || null; }; /** * Convert a value into a string * @param {String | function | undefined} value * @param {String} [defaultValue] * @returns {String} str */ exports.option.asString = function (value, defaultValue) { if (typeof value == 'function') { value = value(); } if (value != null) { return String(value); } return defaultValue || null; }; /** * Convert a size or location into a string with pixels or a percentage * @param {String | Number | function | undefined} value * @param {String} [defaultValue] * @returns {String} size */ exports.option.asSize = function (value, defaultValue) { if (typeof value == 'function') { value = value(); } if (exports.isString(value)) { return value; } else if (exports.isNumber(value)) { return value + 'px'; } else { return defaultValue || null; } }; /** * Convert a value into a DOM element * @param {HTMLElement | function | undefined} value * @param {HTMLElement} [defaultValue] * @returns {HTMLElement | null} dom */ exports.option.asElement = function (value, defaultValue) { if (typeof value == 'function') { value = value(); } return value || defaultValue || null; }; exports.GiveDec = function(Hex) { var Value; if (Hex == "A") Value = 10; else if (Hex == "B") Value = 11; else if (Hex == "C") Value = 12; else if (Hex == "D") Value = 13; else if (Hex == "E") Value = 14; else if (Hex == "F") Value = 15; else Value = eval(Hex); return Value; }; exports.GiveHex = function(Dec) { var Value; if(Dec == 10) Value = "A"; else if (Dec == 11) Value = "B"; else if (Dec == 12) Value = "C"; else if (Dec == 13) Value = "D"; else if (Dec == 14) Value = "E"; else if (Dec == 15) Value = "F"; else Value = "" + Dec; return Value; }; /** * Parse a color property into an object with border, background, and * highlight colors * @param {Object | String} color * @return {Object} colorObject */ exports.parseColor = function(color) { var c; if (exports.isString(color)) { if (exports.isValidRGB(color)) { var rgb = color.substr(4).substr(0,color.length-5).split(','); color = exports.RGBToHex(rgb[0],rgb[1],rgb[2]); } if (exports.isValidHex(color)) { var hsv = exports.hexToHSV(color); var lighterColorHSV = {h:hsv.h,s:hsv.s * 0.45,v:Math.min(1,hsv.v * 1.05)}; var darkerColorHSV = {h:hsv.h,s:Math.min(1,hsv.v * 1.25),v:hsv.v*0.6}; var darkerColorHex = exports.HSVToHex(darkerColorHSV.h ,darkerColorHSV.h ,darkerColorHSV.v); var lighterColorHex = exports.HSVToHex(lighterColorHSV.h,lighterColorHSV.s,lighterColorHSV.v); c = { background: color, border:darkerColorHex, highlight: { background:lighterColorHex, border:darkerColorHex }, hover: { background:lighterColorHex, border:darkerColorHex } }; } else { c = { background:color, border:color, highlight: { background:color, border:color }, hover: { background:color, border:color } }; } } else { c = {}; c.background = color.background || 'white'; c.border = color.border || c.background; if (exports.isString(color.highlight)) { c.highlight = { border: color.highlight, background: color.highlight } } else { c.highlight = {}; c.highlight.background = color.highlight && color.highlight.background || c.background; c.highlight.border = color.highlight && color.highlight.border || c.border; } if (exports.isString(color.hover)) { c.hover = { border: color.hover, background: color.hover } } else { c.hover = {}; c.hover.background = color.hover && color.hover.background || c.background; c.hover.border = color.hover && color.hover.border || c.border; } } return c; }; /** * http://www.yellowpipe.com/yis/tools/hex-to-rgb/color-converter.php * * @param {String} hex * @returns {{r: *, g: *, b: *}} */ exports.hexToRGB = function(hex) { hex = hex.replace("#","").toUpperCase(); var a = exports.GiveDec(hex.substring(0, 1)); var b = exports.GiveDec(hex.substring(1, 2)); var c = exports.GiveDec(hex.substring(2, 3)); var d = exports.GiveDec(hex.substring(3, 4)); var e = exports.GiveDec(hex.substring(4, 5)); var f = exports.GiveDec(hex.substring(5, 6)); var r = (a * 16) + b; var g = (c * 16) + d; var b = (e * 16) + f; return {r:r,g:g,b:b}; }; exports.RGBToHex = function(red,green,blue) { var a = exports.GiveHex(Math.floor(red / 16)); var b = exports.GiveHex(red % 16); var c = exports.GiveHex(Math.floor(green / 16)); var d = exports.GiveHex(green % 16); var e = exports.GiveHex(Math.floor(blue / 16)); var f = exports.GiveHex(blue % 16); var hex = a + b + c + d + e + f; return "#" + hex; }; /** * http://www.javascripter.net/faq/rgb2hsv.htm * * @param red * @param green * @param blue * @returns {*} * @constructor */ exports.RGBToHSV = function(red,green,blue) { red=red/255; green=green/255; blue=blue/255; var minRGB = Math.min(red,Math.min(green,blue)); var maxRGB = Math.max(red,Math.max(green,blue)); // Black-gray-white if (minRGB == maxRGB) { return {h:0,s:0,v:minRGB}; } // Colors other than black-gray-white: var d = (red==minRGB) ? green-blue : ((blue==minRGB) ? red-green : blue-red); var h = (red==minRGB) ? 3 : ((blue==minRGB) ? 1 : 5); var hue = 60*(h - d/(maxRGB - minRGB))/360; var saturation = (maxRGB - minRGB)/maxRGB; var value = maxRGB; return {h:hue,s:saturation,v:value}; }; /** * https://gist.github.com/mjijackson/5311256 * @param h * @param s * @param v * @returns {{r: number, g: number, b: number}} * @constructor */ exports.HSVToRGB = function(h, s, v) { var r, g, b; var i = Math.floor(h * 6); var f = h * 6 - i; var p = v * (1 - s); var q = v * (1 - f * s); var t = v * (1 - (1 - f) * s); switch (i % 6) { case 0: r = v, g = t, b = p; break; case 1: r = q, g = v, b = p; break; case 2: r = p, g = v, b = t; break; case 3: r = p, g = q, b = v; break; case 4: r = t, g = p, b = v; break; case 5: r = v, g = p, b = q; break; } return {r:Math.floor(r * 255), g:Math.floor(g * 255), b:Math.floor(b * 255) }; }; exports.HSVToHex = function(h, s, v) { var rgb = exports.HSVToRGB(h, s, v); return exports.RGBToHex(rgb.r, rgb.g, rgb.b); }; exports.hexToHSV = function(hex) { var rgb = exports.hexToRGB(hex); return exports.RGBToHSV(rgb.r, rgb.g, rgb.b); }; exports.isValidHex = function(hex) { var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex); return isOk; }; exports.isValidRGB = function(rgb) { rgb = rgb.replace(" ",""); var isOk = /rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/i.test(rgb); return isOk; } /** * This recursively redirects the prototype of JSON objects to the referenceObject * This is used for default options. * * @param referenceObject * @returns {*} */ exports.selectiveBridgeObject = function(fields, referenceObject) { if (typeof referenceObject == "object") { var objectTo = Object.create(referenceObject); for (var i = 0; i < fields.length; i++) { if (referenceObject.hasOwnProperty(fields[i])) { if (typeof referenceObject[fields[i]] == "object") { objectTo[fields[i]] = exports.bridgeObject(referenceObject[fields[i]]); } } } return objectTo; } else { return null; } }; /** * This recursively redirects the prototype of JSON objects to the referenceObject * This is used for default options. * * @param referenceObject * @returns {*} */ exports.bridgeObject = function(referenceObject) { if (typeof referenceObject == "object") { var objectTo = Object.create(referenceObject); for (var i in referenceObject) { if (referenceObject.hasOwnProperty(i)) { if (typeof referenceObject[i] == "object") { objectTo[i] = exports.bridgeObject(referenceObject[i]); } } } return objectTo; } else { return null; } }; /** * this is used to set the options of subobjects in the options object. A requirement of these subobjects * is that they have an 'enabled' element which is optional for the user but mandatory for the program. * * @param [object] mergeTarget | this is either this.options or the options used for the groups. * @param [object] options | options * @param [String] option | this is the option key in the options argument * @private */ exports.mergeOptions = function (mergeTarget, options, option) { if (options[option] !== undefined) { if (typeof options[option] == 'boolean') { mergeTarget[option].enabled = options[option]; } else { mergeTarget[option].enabled = true; for (prop in options[option]) { if (options[option].hasOwnProperty(prop)) { mergeTarget[option][prop] = options[option][prop]; } } } } } /** * this is used to set the options of subobjects in the options object. A requirement of these subobjects * is that they have an 'enabled' element which is optional for the user but mandatory for the program. * * @param [object] mergeTarget | this is either this.options or the options used for the groups. * @param [object] options | options * @param [String] option | this is the option key in the options argument * @private */ exports.mergeOptions = function (mergeTarget, options, option) { if (options[option] !== undefined) { if (typeof options[option] == 'boolean') { mergeTarget[option].enabled = options[option]; } else { mergeTarget[option].enabled = true; for (prop in options[option]) { if (options[option].hasOwnProperty(prop)) { mergeTarget[option][prop] = options[option][prop]; } } } } } /** * This function does a binary search for a visible item. The user can select either the this.orderedItems.byStart or .byEnd * arrays. This is done by giving a boolean value true if you want to use the byEnd. * This is done to be able to select the correct if statement (we do not want to check if an item is visible, we want to check * if the time we selected (start or end) is within the current range). * * The trick is that every interval has to either enter the screen at the initial load or by dragging. The case of the ItemRange that is * before and after the current range is handled by simply checking if it was in view before and if it is again. For all the rest, * either the start OR end time has to be in the range. * * @param {Item[]} orderedItems Items ordered by start * @param {{start: number, end: number}} range * @param {String} field * @param {String} field2 * @returns {number} * @private */ exports.binarySearch = function(orderedItems, range, field, field2) { var array = orderedItems; var maxIterations = 10000; var iteration = 0; var found = false; var low = 0; var high = array.length; var newLow = low; var newHigh = high; var guess = Math.floor(0.5*(high+low)); var value; if (high == 0) { guess = -1; } else if (high == 1) { if (array[guess].isVisible(range)) { guess = 0; } else { guess = -1; } } else { high -= 1; while (found == false && iteration < maxIterations) { value = field2 === undefined ? array[guess][field] : array[guess][field][field2]; if (array[guess].isVisible(range)) { found = true; } else { if (value < range.start) { // it is too small --> increase low newLow = Math.floor(0.5*(high+low)); } else { // it is too big --> decrease high newHigh = Math.floor(0.5*(high+low)); } // not in list; if (low == newLow && high == newHigh) { guess = -1; found = true; } else { high = newHigh; low = newLow; guess = Math.floor(0.5*(high+low)); } } iteration++; } if (iteration >= maxIterations) { console.log("BinarySearch too many iterations. Aborting."); } } return guess; }; /** * This function does a binary search for a visible item. The user can select either the this.orderedItems.byStart or .byEnd * arrays. This is done by giving a boolean value true if you want to use the byEnd. * This is done to be able to select the correct if statement (we do not want to check if an item is visible, we want to check * if the time we selected (start or end) is within the current range). * * The trick is that every interval has to either enter the screen at the initial load or by dragging. The case of the ItemRange that is * before and after the current range is handled by simply checking if it was in view before and if it is again. For all the rest, * either the start OR end time has to be in the range. * * @param {Array} orderedItems * @param {{start: number, end: number}} target * @param {String} field * @param {String} sidePreference 'before' or 'after' * @returns {number} * @private */ exports.binarySearchGeneric = function(orderedItems, target, field, sidePreference) { var maxIterations = 10000; var iteration = 0; var array = orderedItems; var found = false; var low = 0; var high = array.length; var newLow = low; var newHigh = high; var guess = Math.floor(0.5*(high+low)); var newGuess; var prevValue, value, nextValue; if (high == 0) {guess = -1;} else if (high == 1) { value = array[guess][field]; if (value == target) { guess = 0; } else { guess = -1; } } else { high -= 1; while (found == false && iteration < maxIterations) { prevValue = array[Math.max(0,guess - 1)][field]; value = array[guess][field]; nextValue = array[Math.min(array.length-1,guess + 1)][field]; if (value == target || prevValue < target && value > target || value < target && nextValue > target) { found = true; if (value != target) { if (sidePreference == 'before') { if (prevValue < target && value > target) { guess = Math.max(0,guess - 1); } } else { if (value < target && nextValue > target) { guess = Math.min(array.length-1,guess + 1); } } } } else { if (value < target) { // it is too small --> increase low newLow = Math.floor(0.5*(high+low)); } else { // it is too big --> decrease high newHigh = Math.floor(0.5*(high+low)); } newGuess = Math.floor(0.5*(high+low)); // not in list; if (low == newLow && high == newHigh) { guess = -1; found = true; } else { high = newHigh; low = newLow; guess = Math.floor(0.5*(high+low)); } } iteration++; } if (iteration >= maxIterations) { console.log("BinarySearch too many iterations. Aborting."); } } return guess; }; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { // DOM utility methods /** * this prepares the JSON container for allocating SVG elements * @param JSONcontainer * @private */ exports.prepareElements = function(JSONcontainer) { // cleanup the redundant svgElements; for (var elementType in JSONcontainer) { if (JSONcontainer.hasOwnProperty(elementType)) { JSONcontainer[elementType].redundant = JSONcontainer[elementType].used; JSONcontainer[elementType].used = []; } } }; /** * this cleans up all the unused SVG elements. By asking for the parentNode, we only need to supply the JSON container from * which to remove the redundant elements. * * @param JSONcontainer * @private */ exports.cleanupElements = function(JSONcontainer) { // cleanup the redundant svgElements; for (var elementType in JSONcontainer) { if (JSONcontainer.hasOwnProperty(elementType)) { if (JSONcontainer[elementType].redundant) { for (var i = 0; i < JSONcontainer[elementType].redundant.length; i++) { JSONcontainer[elementType].redundant[i].parentNode.removeChild(JSONcontainer[elementType].redundant[i]); } JSONcontainer[elementType].redundant = []; } } } }; /** * Allocate or generate an SVG element if needed. Store a reference to it in the JSON container and draw it in the svgContainer * the JSON container and the SVG container have to be supplied so other svg containers (like the legend) can use this. * * @param elementType * @param JSONcontainer * @param svgContainer * @returns {*} * @private */ exports.getSVGElement = function (elementType, JSONcontainer, svgContainer) { var element; // allocate SVG element, if it doesnt yet exist, create one. if (JSONcontainer.hasOwnProperty(elementType)) { // this element has been created before // check if there is an redundant element if (JSONcontainer[elementType].redundant.length > 0) { element = JSONcontainer[elementType].redundant[0]; JSONcontainer[elementType].redundant.shift(); } else { // create a new element and add it to the SVG element = document.createElementNS('http://www.w3.org/2000/svg', elementType); svgContainer.appendChild(element); } } else { // create a new element and add it to the SVG, also create a new object in the svgElements to keep track of it. element = document.createElementNS('http://www.w3.org/2000/svg', elementType); JSONcontainer[elementType] = {used: [], redundant: []}; svgContainer.appendChild(element); } JSONcontainer[elementType].used.push(element); return element; }; /** * Allocate or generate an SVG element if needed. Store a reference to it in the JSON container and draw it in the svgContainer * the JSON container and the SVG container have to be supplied so other svg containers (like the legend) can use this. * * @param elementType * @param JSONcontainer * @param DOMContainer * @returns {*} * @private */ exports.getDOMElement = function (elementType, JSONcontainer, DOMContainer) { var element; // allocate DOM element, if it doesnt yet exist, create one. if (JSONcontainer.hasOwnProperty(elementType)) { // this element has been created before // check if there is an redundant element if (JSONcontainer[elementType].redundant.length > 0) { element = JSONcontainer[elementType].redundant[0]; JSONcontainer[elementType].redundant.shift(); } else { // create a new element and add it to the SVG element = document.createElement(elementType); DOMContainer.appendChild(element); } } else { // create a new element and add it to the SVG, also create a new object in the svgElements to keep track of it. element = document.createElement(elementType); JSONcontainer[elementType] = {used: [], redundant: []}; DOMContainer.appendChild(element); } JSONcontainer[elementType].used.push(element); return element; }; /** * draw a point object. this is a seperate function because it can also be called by the legend. * The reason the JSONcontainer and the target SVG svgContainer have to be supplied is so the legend can use these functions * as well. * * @param x * @param y * @param group * @param JSONcontainer * @param svgContainer * @returns {*} */ exports.drawPoint = function(x, y, group, JSONcontainer, svgContainer) { var point; if (group.options.drawPoints.style == 'circle') { point = exports.getSVGElement('circle',JSONcontainer,svgContainer); point.setAttributeNS(null, "cx", x); point.setAttributeNS(null, "cy", y); point.setAttributeNS(null, "r", 0.5 * group.options.drawPoints.size); point.setAttributeNS(null, "class", group.className + " point"); } else { point = exports.getSVGElement('rect',JSONcontainer,svgContainer); point.setAttributeNS(null, "x", x - 0.5*group.options.drawPoints.size); point.setAttributeNS(null, "y", y - 0.5*group.options.drawPoints.size); point.setAttributeNS(null, "width", group.options.drawPoints.size); point.setAttributeNS(null, "height", group.options.drawPoints.size); point.setAttributeNS(null, "class", group.className + " point"); } return point; }; /** * draw a bar SVG element centered on the X coordinate * * @param x * @param y * @param className */ exports.drawBar = function (x, y, width, height, className, JSONcontainer, svgContainer) { // if (height != 0) { var rect = exports.getSVGElement('rect',JSONcontainer, svgContainer); rect.setAttributeNS(null, "x", x - 0.5 * width); rect.setAttributeNS(null, "y", y); rect.setAttributeNS(null, "width", width); rect.setAttributeNS(null, "height", height); rect.setAttributeNS(null, "class", className); // } }; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); /** * DataSet * * Usage: * var dataSet = new DataSet({ * fieldId: '_id', * type: { * // ... * } * }); * * dataSet.add(item); * dataSet.add(data); * dataSet.update(item); * dataSet.update(data); * dataSet.remove(id); * dataSet.remove(ids); * var data = dataSet.get(); * var data = dataSet.get(id); * var data = dataSet.get(ids); * var data = dataSet.get(ids, options, data); * dataSet.clear(); * * A data set can: * - add/remove/update data * - gives triggers upon changes in the data * - can import/export data in various data formats * * @param {Array | DataTable} [data] Optional array with initial data * @param {Object} [options] Available options: * {String} fieldId Field name of the id in the * items, 'id' by default. * {Object.<String, String} type * A map with field names as key, * and the field type as value. * @constructor DataSet */ // TODO: add a DataSet constructor DataSet(data, options) function DataSet (data, options) { // correctly read optional arguments if (data && !Array.isArray(data) && !util.isDataTable(data)) { options = data; data = null; } this._options = options || {}; this._data = {}; // map with data indexed by id this._fieldId = this._options.fieldId || 'id'; // name of the field containing id this._type = {}; // internal field types (NOTE: this can differ from this._options.type) // all variants of a Date are internally stored as Date, so we can convert // from everything to everything (also from ISODate to Number for example) if (this._options.type) { for (var field in this._options.type) { if (this._options.type.hasOwnProperty(field)) { var value = this._options.type[field]; if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') { this._type[field] = 'Date'; } else { this._type[field] = value; } } } } // TODO: deprecated since version 1.1.1 (or 2.0.0?) if (this._options.convert) { throw new Error('Option "convert" is deprecated. Use "type" instead.'); } this._subscribers = {}; // event subscribers // add initial data when provided if (data) { this.add(data); } } /** * Subscribe to an event, add an event listener * @param {String} event Event name. Available events: 'put', 'update', * 'remove' * @param {function} callback Callback method. Called with three parameters: * {String} event * {Object | null} params * {String | Number} senderId */ DataSet.prototype.on = function(event, callback) { var subscribers = this._subscribers[event]; if (!subscribers) { subscribers = []; this._subscribers[event] = subscribers; } subscribers.push({ callback: callback }); }; // TODO: make this function deprecated (replaced with `on` since version 0.5) DataSet.prototype.subscribe = DataSet.prototype.on; /** * Unsubscribe from an event, remove an event listener * @param {String} event * @param {function} callback */ DataSet.prototype.off = function(event, callback) { var subscribers = this._subscribers[event]; if (subscribers) { this._subscribers[event] = subscribers.filter(function (listener) { return (listener.callback != callback); }); } }; // TODO: make this function deprecated (replaced with `on` since version 0.5) DataSet.prototype.unsubscribe = DataSet.prototype.off; /** * Trigger an event * @param {String} event * @param {Object | null} params * @param {String} [senderId] Optional id of the sender. * @private */ DataSet.prototype._trigger = function (event, params, senderId) { if (event == '*') { throw new Error('Cannot trigger event *'); } var subscribers = []; if (event in this._subscribers) { subscribers = subscribers.concat(this._subscribers[event]); } if ('*' in this._subscribers) { subscribers = subscribers.concat(this._subscribers['*']); } for (var i = 0; i < subscribers.length; i++) { var subscriber = subscribers[i]; if (subscriber.callback) { subscriber.callback(event, params, senderId || null); } } }; /** * Add data. * Adding an item will fail when there already is an item with the same id. * @param {Object | Array | DataTable} data * @param {String} [senderId] Optional sender id * @return {Array} addedIds Array with the ids of the added items */ DataSet.prototype.add = function (data, senderId) { var addedIds = [], id, me = this; if (Array.isArray(data)) { // Array for (var i = 0, len = data.length; i < len; i++) { id = me._addItem(data[i]); addedIds.push(id); } } else if (util.isDataTable(data)) { // Google DataTable var columns = this._getColumnNames(data); for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) { var item = {}; for (var col = 0, cols = columns.length; col < cols; col++) { var field = columns[col]; item[field] = data.getValue(row, col); } id = me._addItem(item); addedIds.push(id); } } else if (data instanceof Object) { // Single item id = me._addItem(data); addedIds.push(id); } else { throw new Error('Unknown dataType'); } if (addedIds.length) { this._trigger('add', {items: addedIds}, senderId); } return addedIds; }; /** * Update existing items. When an item does not exist, it will be created * @param {Object | Array | DataTable} data * @param {String} [senderId] Optional sender id * @return {Array} updatedIds The ids of the added or updated items */ DataSet.prototype.update = function (data, senderId) { var addedIds = [], updatedIds = [], me = this, fieldId = me._fieldId; var addOrUpdate = function (item) { var id = item[fieldId]; if (me._data[id]) { // update item id = me._updateItem(item); updatedIds.push(id); } else { // add new item id = me._addItem(item); addedIds.push(id); } }; if (Array.isArray(data)) { // Array for (var i = 0, len = data.length; i < len; i++) { addOrUpdate(data[i]); } } else if (util.isDataTable(data)) { // Google DataTable var columns = this._getColumnNames(data); for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) { var item = {}; for (var col = 0, cols = columns.length; col < cols; col++) { var field = columns[col]; item[field] = data.getValue(row, col); } addOrUpdate(item); } } else if (data instanceof Object) { // Single item addOrUpdate(data); } else { throw new Error('Unknown dataType'); } if (addedIds.length) { this._trigger('add', {items: addedIds}, senderId); } if (updatedIds.length) { this._trigger('update', {items: updatedIds}, senderId); } return addedIds.concat(updatedIds); }; /** * Get a data item or multiple items. * * Usage: * * get() * get(options: Object) * get(options: Object, data: Array | DataTable) * * get(id: Number | String) * get(id: Number | String, options: Object) * get(id: Number | String, options: Object, data: Array | DataTable) * * get(ids: Number[] | String[]) * get(ids: Number[] | String[], options: Object) * get(ids: Number[] | String[], options: Object, data: Array | DataTable) * * Where: * * {Number | String} id The id of an item * {Number[] | String{}} ids An array with ids of items * {Object} options An Object with options. Available options: * {String} [returnType] Type of data to be * returned. Can be 'DataTable' or 'Array' (default) * {Object.<String, String>} [type] * {String[]} [fields] field names to be returned * {function} [filter] filter items * {String | function} [order] Order the items by * a field name or custom sort function. * {Array | DataTable} [data] If provided, items will be appended to this * array or table. Required in case of Google * DataTable. * * @throws Error */ DataSet.prototype.get = function (args) { var me = this; // parse the arguments var id, ids, options, data; var firstType = util.getType(arguments[0]); if (firstType == 'String' || firstType == 'Number') { // get(id [, options] [, data]) id = arguments[0]; options = arguments[1]; data = arguments[2]; } else if (firstType == 'Array') { // get(ids [, options] [, data]) ids = arguments[0]; options = arguments[1]; data = arguments[2]; } else { // get([, options] [, data]) options = arguments[0]; data = arguments[1]; } // determine the return type var returnType; if (options && options.returnType) { var allowedValues = ["DataTable", "Array", "Object"]; returnType = allowedValues.indexOf(options.returnType) == -1 ? "Array" : options.returnType; if (data && (returnType != util.getType(data))) { throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' + 'does not correspond with specified options.type (' + options.type + ')'); } if (returnType == 'DataTable' && !util.isDataTable(data)) { throw new Error('Parameter "data" must be a DataTable ' + 'when options.type is "DataTable"'); } } else if (data) { returnType = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array'; } else { returnType = 'Array'; } // build options var type = options && options.type || this._options.type; var filter = options && options.filter; var items = [], item, itemId, i, len; // convert items if (id != undefined) { // return a single item item = me._getItem(id, type); if (filter && !filter(item)) { item = null; } } else if (ids != undefined) { // return a subset of items for (i = 0, len = ids.length; i < len; i++) { item = me._getItem(ids[i], type); if (!filter || filter(item)) { items.push(item); } } } else { // return all items for (itemId in this._data) { if (this._data.hasOwnProperty(itemId)) { item = me._getItem(itemId, type); if (!filter || filter(item)) { items.push(item); } } } } // order the results if (options && options.order && id == undefined) { this._sort(items, options.order); } // filter fields of the items if (options && options.fields) { var fields = options.fields; if (id != undefined) { item = this._filterFields(item, fields); } else { for (i = 0, len = items.length; i < len; i++) { items[i] = this._filterFields(items[i], fields); } } } // return the results if (returnType == 'DataTable') { var columns = this._getColumnNames(data); if (id != undefined) { // append a single item to the data table me._appendRow(data, columns, item); } else { // copy the items to the provided data table for (i = 0; i < items.length; i++) { me._appendRow(data, columns, items[i]); } } return data; } else if (returnType == "Object") { var result = {}; for (i = 0; i < items.length; i++) { result[items[i].id] = items[i]; } return result; } else { // return an array if (id != undefined) { // a single item return item; } else { // multiple items if (data) { // copy the items to the provided array for (i = 0, len = items.length; i < len; i++) { data.push(items[i]); } return data; } else { // just return our array return items; } } } }; /** * Get ids of all items or from a filtered set of items. * @param {Object} [options] An Object with options. Available options: * {function} [filter] filter items * {String | function} [order] Order the items by * a field name or custom sort function. * @return {Array} ids */ DataSet.prototype.getIds = function (options) { var data = this._data, filter = options && options.filter, order = options && options.order, type = options && options.type || this._options.type, i, len, id, item, items, ids = []; if (filter) { // get filtered items if (order) { // create ordered list items = []; for (id in data) { if (data.hasOwnProperty(id)) { item = this._getItem(id, type); if (filter(item)) { items.push(item); } } } this._sort(items, order); for (i = 0, len = items.length; i < len; i++) { ids[i] = items[i][this._fieldId]; } } else { // create unordered list for (id in data) { if (data.hasOwnProperty(id)) { item = this._getItem(id, type); if (filter(item)) { ids.push(item[this._fieldId]); } } } } } else { // get all items if (order) { // create an ordered list items = []; for (id in data) { if (data.hasOwnProperty(id)) { items.push(data[id]); } } this._sort(items, order); for (i = 0, len = items.length; i < len; i++) { ids[i] = items[i][this._fieldId]; } } else { // create unordered list for (id in data) { if (data.hasOwnProperty(id)) { item = data[id]; ids.push(item[this._fieldId]); } } } } return ids; }; /** * Returns the DataSet itself. Is overwritten for example by the DataView, * which returns the DataSet it is connected to instead. */ DataSet.prototype.getDataSet = function () { return this; }; /** * Execute a callback function for every item in the dataset. * @param {function} callback * @param {Object} [options] Available options: * {Object.<String, String>} [type] * {String[]} [fields] filter fields * {function} [filter] filter items * {String | function} [order] Order the items by * a field name or custom sort function. */ DataSet.prototype.forEach = function (callback, options) { var filter = options && options.filter, type = options && options.type || this._options.type, data = this._data, item, id; if (options && options.order) { // execute forEach on ordered list var items = this.get(options); for (var i = 0, len = items.length; i < len; i++) { item = items[i]; id = item[this._fieldId]; callback(item, id); } } else { // unordered for (id in data) { if (data.hasOwnProperty(id)) { item = this._getItem(id, type); if (!filter || filter(item)) { callback(item, id); } } } } }; /** * Map every item in the dataset. * @param {function} callback * @param {Object} [options] Available options: * {Object.<String, String>} [type] * {String[]} [fields] filter fields * {function} [filter] filter items * {String | function} [order] Order the items by * a field name or custom sort function. * @return {Object[]} mappedItems */ DataSet.prototype.map = function (callback, options) { var filter = options && options.filter, type = options && options.type || this._options.type, mappedItems = [], data = this._data, item; // convert and filter items for (var id in data) { if (data.hasOwnProperty(id)) { item = this._getItem(id, type); if (!filter || filter(item)) { mappedItems.push(callback(item, id)); } } } // order items if (options && options.order) { this._sort(mappedItems, options.order); } return mappedItems; }; /** * Filter the fields of an item * @param {Object} item * @param {String[]} fields Field names * @return {Object} filteredItem * @private */ DataSet.prototype._filterFields = function (item, fields) { var filteredItem = {}; for (var field in item) { if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) { filteredItem[field] = item[field]; } } return filteredItem; }; /** * Sort the provided array with items * @param {Object[]} items * @param {String | function} order A field name or custom sort function. * @private */ DataSet.prototype._sort = function (items, order) { if (util.isString(order)) { // order by provided field name var name = order; // field name items.sort(function (a, b) { var av = a[name]; var bv = b[name]; return (av > bv) ? 1 : ((av < bv) ? -1 : 0); }); } else if (typeof order === 'function') { // order by sort function items.sort(order); } // TODO: extend order by an Object {field:String, direction:String} // where direction can be 'asc' or 'desc' else { throw new TypeError('Order must be a function or a string'); } }; /** * Remove an object by pointer or by id * @param {String | Number | Object | Array} id Object or id, or an array with * objects or ids to be removed * @param {String} [senderId] Optional sender id * @return {Array} removedIds */ DataSet.prototype.remove = function (id, senderId) { var removedIds = [], i, len, removedId; if (Array.isArray(id)) { for (i = 0, len = id.length; i < len; i++) { removedId = this._remove(id[i]); if (removedId != null) { removedIds.push(removedId); } } } else { removedId = this._remove(id); if (removedId != null) { removedIds.push(removedId); } } if (removedIds.length) { this._trigger('remove', {items: removedIds}, senderId); } return removedIds; }; /** * Remove an item by its id * @param {Number | String | Object} id id or item * @returns {Number | String | null} id * @private */ DataSet.prototype._remove = function (id) { if (util.isNumber(id) || util.isString(id)) { if (this._data[id]) { delete this._data[id]; return id; } } else if (id instanceof Object) { var itemId = id[this._fieldId]; if (itemId && this._data[itemId]) { delete this._data[itemId]; return itemId; } } return null; }; /** * Clear the data * @param {String} [senderId] Optional sender id * @return {Array} removedIds The ids of all removed items */ DataSet.prototype.clear = function (senderId) { var ids = Object.keys(this._data); this._data = {}; this._trigger('remove', {items: ids}, senderId); return ids; }; /** * Find the item with maximum value of a specified field * @param {String} field * @return {Object | null} item Item containing max value, or null if no items */ DataSet.prototype.max = function (field) { var data = this._data, max = null, maxField = null; for (var id in data) { if (data.hasOwnProperty(id)) { var item = data[id]; var itemField = item[field]; if (itemField != null && (!max || itemField > maxField)) { max = item; maxField = itemField; } } } return max; }; /** * Find the item with minimum value of a specified field * @param {String} field * @return {Object | null} item Item containing max value, or null if no items */ DataSet.prototype.min = function (field) { var data = this._data, min = null, minField = null; for (var id in data) { if (data.hasOwnProperty(id)) { var item = data[id]; var itemField = item[field]; if (itemField != null && (!min || itemField < minField)) { min = item; minField = itemField; } } } return min; }; /** * Find all distinct values of a specified field * @param {String} field * @return {Array} values Array containing all distinct values. If data items * do not contain the specified field are ignored. * The returned array is unordered. */ DataSet.prototype.distinct = function (field) { var data = this._data; var values = []; var fieldType = this._options.type && this._options.type[field] || null; var count = 0; var i; for (var prop in data) { if (data.hasOwnProperty(prop)) { var item = data[prop]; var value = item[field]; var exists = false; for (i = 0; i < count; i++) { if (values[i] == value) { exists = true; break; } } if (!exists && (value !== undefined)) { values[count] = value; count++; } } } if (fieldType) { for (i = 0; i < values.length; i++) { values[i] = util.convert(values[i], fieldType); } } return values; }; /** * Add a single item. Will fail when an item with the same id already exists. * @param {Object} item * @return {String} id * @private */ DataSet.prototype._addItem = function (item) { var id = item[this._fieldId]; if (id != undefined) { // check whether this id is already taken if (this._data[id]) { // item already exists throw new Error('Cannot add item: item with id ' + id + ' already exists'); } } else { // generate an id id = util.randomUUID(); item[this._fieldId] = id; } var d = {}; for (var field in item) { if (item.hasOwnProperty(field)) { var fieldType = this._type[field]; // type may be undefined d[field] = util.convert(item[field], fieldType); } } this._data[id] = d; return id; }; /** * Get an item. Fields can be converted to a specific type * @param {String} id * @param {Object.<String, String>} [types] field types to convert * @return {Object | null} item * @private */ DataSet.prototype._getItem = function (id, types) { var field, value; // get the item from the dataset var raw = this._data[id]; if (!raw) { return null; } // convert the items field types var converted = {}; if (types) { for (field in raw) { if (raw.hasOwnProperty(field)) { value = raw[field]; converted[field] = util.convert(value, types[field]); } } } else { // no field types specified, no converting needed for (field in raw) { if (raw.hasOwnProperty(field)) { value = raw[field]; converted[field] = value; } } } return converted; }; /** * Update a single item: merge with existing item. * Will fail when the item has no id, or when there does not exist an item * with the same id. * @param {Object} item * @return {String} id * @private */ DataSet.prototype._updateItem = function (item) { var id = item[this._fieldId]; if (id == undefined) { throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')'); } var d = this._data[id]; if (!d) { // item doesn't exist throw new Error('Cannot update item: no item with id ' + id + ' found'); } // merge with current item for (var field in item) { if (item.hasOwnProperty(field)) { var fieldType = this._type[field]; // type may be undefined d[field] = util.convert(item[field], fieldType); } } return id; }; /** * Get an array with the column names of a Google DataTable * @param {DataTable} dataTable * @return {String[]} columnNames * @private */ DataSet.prototype._getColumnNames = function (dataTable) { var columns = []; for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) { columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col); } return columns; }; /** * Append an item as a row to the dataTable * @param dataTable * @param columns * @param item * @private */ DataSet.prototype._appendRow = function (dataTable, columns, item) { var row = dataTable.addRow(); for (var col = 0, cols = columns.length; col < cols; col++) { var field = columns[col]; dataTable.setValue(row, col, item[field]); } }; module.exports = DataSet; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var DataSet = __webpack_require__(3); /** * DataView * * a dataview offers a filtered view on a dataset or an other dataview. * * @param {DataSet | DataView} data * @param {Object} [options] Available options: see method get * * @constructor DataView */ function DataView (data, options) { this._data = null; this._ids = {}; // ids of the items currently in memory (just contains a boolean true) this._options = options || {}; this._fieldId = 'id'; // name of the field containing id this._subscribers = {}; // event subscribers var me = this; this.listener = function () { me._onEvent.apply(me, arguments); }; this.setData(data); } // TODO: implement a function .config() to dynamically update things like configured filter // and trigger changes accordingly /** * Set a data source for the view * @param {DataSet | DataView} data */ DataView.prototype.setData = function (data) { var ids, i, len; if (this._data) { // unsubscribe from current dataset if (this._data.unsubscribe) { this._data.unsubscribe('*', this.listener); } // trigger a remove of all items in memory ids = []; for (var id in this._ids) { if (this._ids.hasOwnProperty(id)) { ids.push(id); } } this._ids = {}; this._trigger('remove', {items: ids}); } this._data = data; if (this._data) { // update fieldId this._fieldId = this._options.fieldId || (this._data && this._data.options && this._data.options.fieldId) || 'id'; // trigger an add of all added items ids = this._data.getIds({filter: this._options && this._options.filter}); for (i = 0, len = ids.length; i < len; i++) { id = ids[i]; this._ids[id] = true; } this._trigger('add', {items: ids}); // subscribe to new dataset if (this._data.on) { this._data.on('*', this.listener); } } }; /** * Get data from the data view * * Usage: * * get() * get(options: Object) * get(options: Object, data: Array | DataTable) * * get(id: Number) * get(id: Number, options: Object) * get(id: Number, options: Object, data: Array | DataTable) * * get(ids: Number[]) * get(ids: Number[], options: Object) * get(ids: Number[], options: Object, data: Array | DataTable) * * Where: * * {Number | String} id The id of an item * {Number[] | String{}} ids An array with ids of items * {Object} options An Object with options. Available options: * {String} [type] Type of data to be returned. Can * be 'DataTable' or 'Array' (default) * {Object.<String, String>} [convert] * {String[]} [fields] field names to be returned * {function} [filter] filter items * {String | function} [order] Order the items by * a field name or custom sort function. * {Array | DataTable} [data] If provided, items will be appended to this * array or table. Required in case of Google * DataTable. * @param args */ DataView.prototype.get = function (args) { var me = this; // parse the arguments var ids, options, data; var firstType = util.getType(arguments[0]); if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') { // get(id(s) [, options] [, data]) ids = arguments[0]; // can be a single id or an array with ids options = arguments[1]; data = arguments[2]; } else { // get([, options] [, data]) options = arguments[0]; data = arguments[1]; } // extend the options with the default options and provided options var viewOptions = util.extend({}, this._options, options); // create a combined filter method when needed if (this._options.filter && options && options.filter) { viewOptions.filter = function (item) { return me._options.filter(item) && options.filter(item); } } // build up the call to the linked data set var getArguments = []; if (ids != undefined) { getArguments.push(ids); } getArguments.push(viewOptions); getArguments.push(data); return this._data && this._data.get.apply(this._data, getArguments); }; /** * Get ids of all items or from a filtered set of items. * @param {Object} [options] An Object with options. Available options: * {function} [filter] filter items * {String | function} [order] Order the items by * a field name or custom sort function. * @return {Array} ids */ DataView.prototype.getIds = function (options) { var ids; if (this._data) { var defaultFilter = this._options.filter; var filter; if (options && options.filter) { if (defaultFilter) { filter = function (item) { return defaultFilter(item) && options.filter(item); } } else { filter = options.filter; } } else { filter = defaultFilter; } ids = this._data.getIds({ filter: filter, order: options && options.order }); } else { ids = []; } return ids; }; /** * Get the DataSet to which this DataView is connected. In case there is a chain * of multiple DataViews, the root DataSet of this chain is returned. * @return {DataSet} dataSet */ DataView.prototype.getDataSet = function () { var dataSet = this; while (dataSet instanceof DataView) { dataSet = dataSet._data; } return dataSet || null; }; /** * Event listener. Will propagate all events from the connected data set to * the subscribers of the DataView, but will filter the items and only trigger * when there are changes in the filtered data set. * @param {String} event * @param {Object | null} params * @param {String} senderId * @private */ DataView.prototype._onEvent = function (event, params, senderId) { var i, len, id, item, ids = params && params.items, data = this._data, added = [], updated = [], removed = []; if (ids && data) { switch (event) { case 'add': // filter the ids of the added items for (i = 0, len = ids.length; i < len; i++) { id = ids[i]; item = this.get(id); if (item) { this._ids[id] = true; added.push(id); } } break; case 'update': // determine the event from the views viewpoint: an updated // item can be added, updated, or removed from this view. for (i = 0, len = ids.length; i < len; i++) { id = ids[i]; item = this.get(id); if (item) { if (this._ids[id]) { updated.push(id); } else { this._ids[id] = true; added.push(id); } } else { if (this._ids[id]) { delete this._ids[id]; removed.push(id); } else { // nothing interesting for me :-( } } } break; case 'remove': // filter the ids of the removed items for (i = 0, len = ids.length; i < len; i++) { id = ids[i]; if (this._ids[id]) { delete this._ids[id]; removed.push(id); } } break; } if (added.length) { this._trigger('add', {items: added}, senderId); } if (updated.length) { this._trigger('update', {items: updated}, senderId); } if (removed.length) { this._trigger('remove', {items: removed}, senderId); } } }; // copy subscription functionality from DataSet DataView.prototype.on = DataSet.prototype.on; DataView.prototype.off = DataSet.prototype.off; DataView.prototype._trigger = DataSet.prototype._trigger; // TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5) DataView.prototype.subscribe = DataView.prototype.on; DataView.prototype.unsubscribe = DataView.prototype.off; module.exports = DataView; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { var Emitter = __webpack_require__(46); var DataSet = __webpack_require__(3); var DataView = __webpack_require__(4); var util = __webpack_require__(1); var Point3d = __webpack_require__(9); var Point2d = __webpack_require__(8); var Camera = __webpack_require__(6); var Filter = __webpack_require__(7); var Slider = __webpack_require__(10); var StepNumber = __webpack_require__(11); /** * @constructor Graph3d * Graph3d displays data in 3d. * * Graph3d is developed in javascript as a Google Visualization Chart. * * @param {Element} container The DOM element in which the Graph3d will * be created. Normally a div element. * @param {DataSet | DataView | Array} [data] * @param {Object} [options] */ function Graph3d(container, data, options) { if (!(this instanceof Graph3d)) { throw new SyntaxError('Constructor must be called with the new operator'); } // create variables and set default values this.containerElement = container; this.width = '400px'; this.height = '400px'; this.margin = 10; // px this.defaultXCenter = '55%'; this.defaultYCenter = '50%'; this.xLabel = 'x'; this.yLabel = 'y'; this.zLabel = 'z'; this.filterLabel = 'time'; this.legendLabel = 'value'; this.style = Graph3d.STYLE.DOT; this.showPerspective = true; this.showGrid = true; this.keepAspectRatio = true; this.showShadow = false; this.showGrayBottom = false; // TODO: this does not work correctly this.showTooltip = false; this.verticalRatio = 0.5; // 0.1 to 1.0, where 1.0 results in a 'cube' this.animationInterval = 1000; // milliseconds this.animationPreload = false; this.camera = new Camera(); this.eye = new Point3d(0, 0, -1); // TODO: set eye.z about 3/4 of the width of the window? this.dataTable = null; // The original data table this.dataPoints = null; // The table with point objects // the column indexes this.colX = undefined; this.colY = undefined; this.colZ = undefined; this.colValue = undefined; this.colFilter = undefined; this.xMin = 0; this.xStep = undefined; // auto by default this.xMax = 1; this.yMin = 0; this.yStep = undefined; // auto by default this.yMax = 1; this.zMin = 0; this.zStep = undefined; // auto by default this.zMax = 1; this.valueMin = 0; this.valueMax = 1; this.xBarWidth = 1; this.yBarWidth = 1; // TODO: customize axis range // constants this.colorAxis = '#4D4D4D'; this.colorGrid = '#D3D3D3'; this.colorDot = '#7DC1FF'; this.colorDotBorder = '#3267D2'; // create a frame and canvas this.create(); // apply options (also when undefined) this.setOptions(options); // apply data if (data) { this.setData(data); } } // Extend Graph3d with an Emitter mixin Emitter(Graph3d.prototype); /** * Calculate the scaling values, dependent on the range in x, y, and z direction */ Graph3d.prototype._setScale = function() { this.scale = new Point3d(1 / (this.xMax - this.xMin), 1 / (this.yMax - this.yMin), 1 / (this.zMax - this.zMin)); // keep aspect ration between x and y scale if desired if (this.keepAspectRatio) { if (this.scale.x < this.scale.y) { //noinspection JSSuspiciousNameCombination this.scale.y = this.scale.x; } else { //noinspection JSSuspiciousNameCombination this.scale.x = this.scale.y; } } // scale the vertical axis this.scale.z *= this.verticalRatio; // TODO: can this be automated? verticalRatio? // determine scale for (optional) value this.scale.value = 1 / (this.valueMax - this.valueMin); // position the camera arm var xCenter = (this.xMax + this.xMin) / 2 * this.scale.x; var yCenter = (this.yMax + this.yMin) / 2 * this.scale.y; var zCenter = (this.zMax + this.zMin) / 2 * this.scale.z; this.camera.setArmLocation(xCenter, yCenter, zCenter); }; /** * Convert a 3D location to a 2D location on screen * http://en.wikipedia.org/wiki/3D_projection * @param {Point3d} point3d A 3D point with parameters x, y, z * @return {Point2d} point2d A 2D point with parameters x, y */ Graph3d.prototype._convert3Dto2D = function(point3d) { var translation = this._convertPointToTranslation(point3d); return this._convertTranslationToScreen(translation); }; /** * Convert a 3D location its translation seen from the camera * http://en.wikipedia.org/wiki/3D_projection * @param {Point3d} point3d A 3D point with parameters x, y, z * @return {Point3d} translation A 3D point with parameters x, y, z This is * the translation of the point, seen from the * camera */ Graph3d.prototype._convertPointToTranslation = function(point3d) { var ax = point3d.x * this.scale.x, ay = point3d.y * this.scale.y, az = point3d.z * this.scale.z, cx = this.camera.getCameraLocation().x, cy = this.camera.getCameraLocation().y, cz = this.camera.getCameraLocation().z, // calculate angles sinTx = Math.sin(this.camera.getCameraRotation().x), cosTx = Math.cos(this.camera.getCameraRotation().x), sinTy = Math.sin(this.camera.getCameraRotation().y), cosTy = Math.cos(this.camera.getCameraRotation().y), sinTz = Math.sin(this.camera.getCameraRotation().z), cosTz = Math.cos(this.camera.getCameraRotation().z), // calculate translation dx = cosTy * (sinTz * (ay - cy) + cosTz * (ax - cx)) - sinTy * (az - cz), dy = sinTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) + cosTx * (cosTz * (ay - cy) - sinTz * (ax-cx)), dz = cosTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) - sinTx * (cosTz * (ay - cy) - sinTz * (ax-cx)); return new Point3d(dx, dy, dz); }; /** * Convert a translation point to a point on the screen * @param {Point3d} translation A 3D point with parameters x, y, z This is * the translation of the point, seen from the * camera * @return {Point2d} point2d A 2D point with parameters x, y */ Graph3d.prototype._convertTranslationToScreen = function(translation) { var ex = this.eye.x, ey = this.eye.y, ez = this.eye.z, dx = translation.x, dy = translation.y, dz = translation.z; // calculate position on screen from translation var bx; var by; if (this.showPerspective) { bx = (dx - ex) * (ez / dz); by = (dy - ey) * (ez / dz); } else { bx = dx * -(ez / this.camera.getArmLength()); by = dy * -(ez / this.camera.getArmLength()); } // shift and scale the point to the center of the screen // use the width of the graph to scale both horizontally and vertically. return new Point2d( this.xcenter + bx * this.frame.canvas.clientWidth, this.ycenter - by * this.frame.canvas.clientWidth); }; /** * Set the background styling for the graph * @param {string | {fill: string, stroke: string, strokeWidth: string}} backgroundColor */ Graph3d.prototype._setBackgroundColor = function(backgroundColor) { var fill = 'white'; var stroke = 'gray'; var strokeWidth = 1; if (typeof(backgroundColor) === 'string') { fill = backgroundColor; stroke = 'none'; strokeWidth = 0; } else if (typeof(backgroundColor) === 'object') { if (backgroundColor.fill !== undefined) fill = backgroundColor.fill; if (backgroundColor.stroke !== undefined) stroke = backgroundColor.stroke; if (backgroundColor.strokeWidth !== undefined) strokeWidth = backgroundColor.strokeWidth; } else if (backgroundColor === undefined) { // use use defaults } else { throw 'Unsupported type of backgroundColor'; } this.frame.style.backgroundColor = fill; this.frame.style.borderColor = stroke; this.frame.style.borderWidth = strokeWidth + 'px'; this.frame.style.borderStyle = 'solid'; }; /// enumerate the available styles Graph3d.STYLE = { BAR: 0, BARCOLOR: 1, BARSIZE: 2, DOT : 3, DOTLINE : 4, DOTCOLOR: 5, DOTSIZE: 6, GRID : 7, LINE: 8, SURFACE : 9 }; /** * Retrieve the style index from given styleName * @param {string} styleName Style name such as 'dot', 'grid', 'dot-line' * @return {Number} styleNumber Enumeration value representing the style, or -1 * when not found */ Graph3d.prototype._getStyleNumber = function(styleName) { switch (styleName) { case 'dot': return Graph3d.STYLE.DOT; case 'dot-line': return Graph3d.STYLE.DOTLINE; case 'dot-color': return Graph3d.STYLE.DOTCOLOR; case 'dot-size': return Graph3d.STYLE.DOTSIZE; case 'line': return Graph3d.STYLE.LINE; case 'grid': return Graph3d.STYLE.GRID; case 'surface': return Graph3d.STYLE.SURFACE; case 'bar': return Graph3d.STYLE.BAR; case 'bar-color': return Graph3d.STYLE.BARCOLOR; case 'bar-size': return Graph3d.STYLE.BARSIZE; } return -1; }; /** * Determine the indexes of the data columns, based on the given style and data * @param {DataSet} data * @param {Number} style */ Graph3d.prototype._determineColumnIndexes = function(data, style) { if (this.style === Graph3d.STYLE.DOT || this.style === Graph3d.STYLE.DOTLINE || this.style === Graph3d.STYLE.LINE || this.style === Graph3d.STYLE.GRID || this.style === Graph3d.STYLE.SURFACE || this.style === Graph3d.STYLE.BAR) { // 3 columns expected, and optionally a 4th with filter values this.colX = 0; this.colY = 1; this.colZ = 2; this.colValue = undefined; if (data.getNumberOfColumns() > 3) { this.colFilter = 3; } } else if (this.style === Graph3d.STYLE.DOTCOLOR || this.style === Graph3d.STYLE.DOTSIZE || this.style === Graph3d.STYLE.BARCOLOR || this.style === Graph3d.STYLE.BARSIZE) { // 4 columns expected, and optionally a 5th with filter values this.colX = 0; this.colY = 1; this.colZ = 2; this.colValue = 3; if (data.getNumberOfColumns() > 4) { this.colFilter = 4; } } else { throw 'Unknown style "' + this.style + '"'; } }; Graph3d.prototype.getNumberOfRows = function(data) { return data.length; } Graph3d.prototype.getNumberOfColumns = function(data) { var counter = 0; for (var column in data[0]) { if (data[0].hasOwnProperty(column)) { counter++; } } return counter; } Graph3d.prototype.getDistinctValues = function(data, column) { var distinctValues = []; for (var i = 0; i < data.length; i++) { if (distinctValues.indexOf(data[i][column]) == -1) { distinctValues.push(data[i][column]); } } return distinctValues; } Graph3d.prototype.getColumnRange = function(data,column) { var minMax = {min:data[0][column],max:data[0][column]}; for (var i = 0; i < data.length; i++) { if (minMax.min > data[i][column]) { minMax.min = data[i][column]; } if (minMax.max < data[i][column]) { minMax.max = data[i][column]; } } return minMax; }; /** * Initialize the data from the data table. Calculate minimum and maximum values * and column index values * @param {Array | DataSet | DataView} rawData The data containing the items for the Graph. * @param {Number} style Style Number */ Graph3d.prototype._dataInitialize = function (rawData, style) { var me = this; // unsubscribe from the dataTable if (this.dataSet) { this.dataSet.off('*', this._onChange); } if (rawData === undefined) return; if (Array.isArray(rawData)) { rawData = new DataSet(rawData); } var data; if (rawData instanceof DataSet || rawData instanceof DataView) { data = rawData.get(); } else { throw new Error('Array, DataSet, or DataView expected'); } if (data.length == 0) return; this.dataSet = rawData; this.dataTable = data; // subscribe to changes in the dataset this._onChange = function () { me.setData(me.dataSet); }; this.dataSet.on('*', this._onChange); // _determineColumnIndexes // getNumberOfRows (points) // getNumberOfColumns (x,y,z,v,t,t1,t2...) // getDistinctValues (unique values?) // getColumnRange // determine the location of x,y,z,value,filter columns this.colX = 'x'; this.colY = 'y'; this.colZ = 'z'; this.colValue = 'style'; this.colFilter = 'filter'; // check if a filter column is provided if (data[0].hasOwnProperty('filter')) { if (this.dataFilter === undefined) { this.dataFilter = new Filter(rawData, this.colFilter, this); this.dataFilter.setOnLoadCallback(function() {me.redraw();}); } } var withBars = this.style == Graph3d.STYLE.BAR || this.style == Graph3d.STYLE.BARCOLOR || this.style == Graph3d.STYLE.BARSIZE; // determine barWidth from data if (withBars) { if (this.defaultXBarWidth !== undefined) { this.xBarWidth = this.defaultXBarWidth; } else { var dataX = this.getDistinctValues(data,this.colX); this.xBarWidth = (dataX[1] - dataX[0]) || 1; } if (this.defaultYBarWidth !== undefined) { this.yBarWidth = this.defaultYBarWidth; } else { var dataY = this.getDistinctValues(data,this.colY); this.yBarWidth = (dataY[1] - dataY[0]) || 1; } } // calculate minimums and maximums var xRange = this.getColumnRange(data,this.colX); if (withBars) { xRange.min -= this.xBarWidth / 2; xRange.max += this.xBarWidth / 2; } this.xMin = (this.defaultXMin !== undefined) ? this.defaultXMin : xRange.min; this.xMax = (this.defaultXMax !== undefined) ? this.defaultXMax : xRange.max; if (this.xMax <= this.xMin) this.xMax = this.xMin + 1; this.xStep = (this.defaultXStep !== undefined) ? this.defaultXStep : (this.xMax-this.xMin)/5; var yRange = this.getColumnRange(data,this.colY); if (withBars) { yRange.min -= this.yBarWidth / 2; yRange.max += this.yBarWidth / 2; } this.yMin = (this.defaultYMin !== undefined) ? this.defaultYMin : yRange.min; this.yMax = (this.defaultYMax !== undefined) ? this.defaultYMax : yRange.max; if (this.yMax <= this.yMin) this.yMax = this.yMin + 1; this.yStep = (this.defaultYStep !== undefined) ? this.defaultYStep : (this.yMax-this.yMin)/5; var zRange = this.getColumnRange(data,this.colZ); this.zMin = (this.defaultZMin !== undefined) ? this.defaultZMin : zRange.min; this.zMax = (this.defaultZMax !== undefined) ? this.defaultZMax : zRange.max; if (this.zMax <= this.zMin) this.zMax = this.zMin + 1; this.zStep = (this.defaultZStep !== undefined) ? this.defaultZStep : (this.zMax-this.zMin)/5; if (this.colValue !== undefined) { var valueRange = this.getColumnRange(data,this.colValue); this.valueMin = (this.defaultValueMin !== undefined) ? this.defaultValueMin : valueRange.min; this.valueMax = (this.defaultValueMax !== undefined) ? this.defaultValueMax : valueRange.max; if (this.valueMax <= this.valueMin) this.valueMax = this.valueMin + 1; } // set the scale dependent on the ranges. this._setScale(); }; /** * Filter the data based on the current filter * @param {Array} data * @return {Array} dataPoints Array with point objects which can be drawn on screen */ Graph3d.prototype._getDataPoints = function (data) { // TODO: store the created matrix dataPoints in the filters instead of reloading each time var x, y, i, z, obj, point; var dataPoints = []; if (this.style === Graph3d.STYLE.GRID || this.style === Graph3d.STYLE.SURFACE) { // copy all values from the google data table to a matrix // the provided values are supposed to form a grid of (x,y) positions // create two lists with all present x and y values var dataX = []; var dataY = []; for (i = 0; i < this.getNumberOfRows(data); i++) { x = data[i][this.colX] || 0; y = data[i][this.colY] || 0; if (dataX.indexOf(x) === -1) { dataX.push(x); } if (dataY.indexOf(y) === -1) { dataY.push(y); } } function sortNumber(a, b) { return a - b; } dataX.sort(sortNumber); dataY.sort(sortNumber); // create a grid, a 2d matrix, with all values. var dataMatrix = []; // temporary data matrix for (i = 0; i < data.length; i++) { x = data[i][this.colX] || 0; y = data[i][this.colY] || 0; z = data[i][this.colZ] || 0; var xIndex = dataX.indexOf(x); // TODO: implement Array().indexOf() for Internet Explorer var yIndex = dataY.indexOf(y); if (dataMatrix[xIndex] === undefined) { dataMatrix[xIndex] = []; } var point3d = new Point3d(); point3d.x = x; point3d.y = y; point3d.z = z; obj = {}; obj.point = point3d; obj.trans = undefined; obj.screen = undefined; obj.bottom = new Point3d(x, y, this.zMin); dataMatrix[xIndex][yIndex] = obj; dataPoints.push(obj); } // fill in the pointers to the neighbors. for (x = 0; x < dataMatrix.length; x++) { for (y = 0; y < dataMatrix[x].length; y++) { if (dataMatrix[x][y]) { dataMatrix[x][y].pointRight = (x < dataMatrix.length-1) ? dataMatrix[x+1][y] : undefined; dataMatrix[x][y].pointTop = (y < dataMatrix[x].length-1) ? dataMatrix[x][y+1] : undefined; dataMatrix[x][y].pointCross = (x < dataMatrix.length-1 && y < dataMatrix[x].length-1) ? dataMatrix[x+1][y+1] : undefined; } } } } else { // 'dot', 'dot-line', etc. // copy all values from the google data table to a list with Point3d objects for (i = 0; i < data.length; i++) { point = new Point3d(); point.x = data[i][this.colX] || 0; point.y = data[i][this.colY] || 0; point.z = data[i][this.colZ] || 0; if (this.colValue !== undefined) { point.value = data[i][this.colValue] || 0; } obj = {}; obj.point = point; obj.bottom = new Point3d(point.x, point.y, this.zMin); obj.trans = undefined; obj.screen = undefined; dataPoints.push(obj); } } return dataPoints; }; /** * Create the main frame for the Graph3d. * This function is executed once when a Graph3d object is created. The frame * contains a canvas, and this canvas contains all objects like the axis and * nodes. */ Graph3d.prototype.create = function () { // remove all elements from the container element. while (this.containerElement.hasChildNodes()) { this.containerElement.removeChild(this.containerElement.firstChild); } this.frame = document.createElement('div'); this.frame.style.position = 'relative'; this.frame.style.overflow = 'hidden'; // create the graph canvas (HTML canvas element) this.frame.canvas = document.createElement( 'canvas' ); this.frame.canvas.style.position = 'relative'; this.frame.appendChild(this.frame.canvas); //if (!this.frame.canvas.getContext) { { var noCanvas = document.createElement( 'DIV' ); noCanvas.style.color = 'red'; noCanvas.style.fontWeight = 'bold' ; noCanvas.style.padding = '10px'; noCanvas.innerHTML = 'Error: your browser does not support HTML canvas'; this.frame.canvas.appendChild(noCanvas); } this.frame.filter = document.createElement( 'div' ); this.frame.filter.style.position = 'absolute'; this.frame.filter.style.bottom = '0px'; this.frame.filter.style.left = '0px'; this.frame.filter.style.width = '100%'; this.frame.appendChild(this.frame.filter); // add event listeners to handle moving and zooming the contents var me = this; var onmousedown = function (event) {me._onMouseDown(event);}; var ontouchstart = function (event) {me._onTouchStart(event);}; var onmousewheel = function (event) {me._onWheel(event);}; var ontooltip = function (event) {me._onTooltip(event);}; // TODO: these events are never cleaned up... can give a 'memory leakage' util.addEventListener(this.frame.canvas, 'keydown', onkeydown); util.addEventListener(this.frame.canvas, 'mousedown', onmousedown); util.addEventListener(this.frame.canvas, 'touchstart', ontouchstart); util.addEventListener(this.frame.canvas, 'mousewheel', onmousewheel); util.addEventListener(this.frame.canvas, 'mousemove', ontooltip); // add the new graph to the container element this.containerElement.appendChild(this.frame); }; /** * Set a new size for the graph * @param {string} width Width in pixels or percentage (for example '800px' * or '50%') * @param {string} height Height in pixels or percentage (for example '400px' * or '30%') */ Graph3d.prototype.setSize = function(width, height) { this.frame.style.width = width; this.frame.style.height = height; this._resizeCanvas(); }; /** * Resize the canvas to the current size of the frame */ Graph3d.prototype._resizeCanvas = function() { this.frame.canvas.style.width = '100%'; this.frame.canvas.style.height = '100%'; this.frame.canvas.width = this.frame.canvas.clientWidth; this.frame.canvas.height = this.frame.canvas.clientHeight; // adjust with for margin this.frame.filter.style.width = (this.frame.canvas.clientWidth - 2 * 10) + 'px'; }; /** * Start animation */ Graph3d.prototype.animationStart = function() { if (!this.frame.filter || !this.frame.filter.slider) throw 'No animation available'; this.frame.filter.slider.play(); }; /** * Stop animation */ Graph3d.prototype.animationStop = function() { if (!this.frame.filter || !this.frame.filter.slider) return; this.frame.filter.slider.stop(); }; /** * Resize the center position based on the current values in this.defaultXCenter * and this.defaultYCenter (which are strings with a percentage or a value * in pixels). The center positions are the variables this.xCenter * and this.yCenter */ Graph3d.prototype._resizeCenter = function() { // calculate the horizontal center position if (this.defaultXCenter.charAt(this.defaultXCenter.length-1) === '%') { this.xcenter = parseFloat(this.defaultXCenter) / 100 * this.frame.canvas.clientWidth; } else { this.xcenter = parseFloat(this.defaultXCenter); // supposed to be in px } // calculate the vertical center position if (this.defaultYCenter.charAt(this.defaultYCenter.length-1) === '%') { this.ycenter = parseFloat(this.defaultYCenter) / 100 * (this.frame.canvas.clientHeight - this.frame.filter.clientHeight); } else { this.ycenter = parseFloat(this.defaultYCenter); // supposed to be in px } }; /** * Set the rotation and distance of the camera * @param {Object} pos An object with the camera position. The object * contains three parameters: * - horizontal {Number} * The horizontal rotation, between 0 and 2*PI. * Optional, can be left undefined. * - vertical {Number} * The vertical rotation, between 0 and 0.5*PI * if vertical=0.5*PI, the graph is shown from the * top. Optional, can be left undefined. * - distance {Number} * The (normalized) distance of the camera to the * center of the graph, a value between 0.71 and 5.0. * Optional, can be left undefined. */ Graph3d.prototype.setCameraPosition = function(pos) { if (pos === undefined) { return; } if (pos.horizontal !== undefined && pos.vertical !== undefined) { this.camera.setArmRotation(pos.horizontal, pos.vertical); } if (pos.distance !== undefined) { this.camera.setArmLength(pos.distance); } this.redraw(); }; /** * Retrieve the current camera rotation * @return {object} An object with parameters horizontal, vertical, and * distance */ Graph3d.prototype.getCameraPosition = function() { var pos = this.camera.getArmRotation(); pos.distance = this.camera.getArmLength(); return pos; }; /** * Load data into the 3D Graph */ Graph3d.prototype._readData = function(data) { // read the data this._dataInitialize(data, this.style); if (this.dataFilter) { // apply filtering this.dataPoints = this.dataFilter._getDataPoints(); } else { // no filtering. load all data this.dataPoints = this._getDataPoints(this.dataTable); } // draw the filter this._redrawFilter(); }; /** * Replace the dataset of the Graph3d * @param {Array | DataSet | DataView} data */ Graph3d.prototype.setData = function (data) { this._readData(data); this.redraw(); // start animation when option is true if (this.animationAutoStart && this.dataFilter) { this.animationStart(); } }; /** * Update the options. Options will be merged with current options * @param {Object} options */ Graph3d.prototype.setOptions = function (options) { var cameraPosition = undefined; this.animationStop(); if (options !== undefined) { // retrieve parameter values if (options.width !== undefined) this.width = options.width; if (options.height !== undefined) this.height = options.height; if (options.xCenter !== undefined) this.defaultXCenter = options.xCenter; if (options.yCenter !== undefined) this.defaultYCenter = options.yCenter; if (options.filterLabel !== undefined) this.filterLabel = options.filterLabel; if (options.legendLabel !== undefined) this.legendLabel = options.legendLabel; if (options.xLabel !== undefined) this.xLabel = options.xLabel; if (options.yLabel !== undefined) this.yLabel = options.yLabel; if (options.zLabel !== undefined) this.zLabel = options.zLabel; if (options.style !== undefined) { var styleNumber = this._getStyleNumber(options.style); if (styleNumber !== -1) { this.style = styleNumber; } } if (options.showGrid !== undefined) this.showGrid = options.showGrid; if (options.showPerspective !== undefined) this.showPerspective = options.showPerspective; if (options.showShadow !== undefined) this.showShadow = options.showShadow; if (options.tooltip !== undefined) this.showTooltip = options.tooltip; if (options.showAnimationControls !== undefined) this.showAnimationControls = options.showAnimationControls; if (options.keepAspectRatio !== undefined) this.keepAspectRatio = options.keepAspectRatio; if (options.verticalRatio !== undefined) this.verticalRatio = options.verticalRatio; if (options.animationInterval !== undefined) this.animationInterval = options.animationInterval; if (options.animationPreload !== undefined) this.animationPreload = options.animationPreload; if (options.animationAutoStart !== undefined)this.animationAutoStart = options.animationAutoStart; if (options.xBarWidth !== undefined) this.defaultXBarWidth = options.xBarWidth; if (options.yBarWidth !== undefined) this.defaultYBarWidth = options.yBarWidth; if (options.xMin !== undefined) this.defaultXMin = options.xMin; if (options.xStep !== undefined) this.defaultXStep = options.xStep; if (options.xMax !== undefined) this.defaultXMax = options.xMax; if (options.yMin !== undefined) this.defaultYMin = options.yMin; if (options.yStep !== undefined) this.defaultYStep = options.yStep; if (options.yMax !== undefined) this.defaultYMax = options.yMax; if (options.zMin !== undefined) this.defaultZMin = options.zMin; if (options.zStep !== undefined) this.defaultZStep = options.zStep; if (options.zMax !== undefined) this.defaultZMax = options.zMax; if (options.valueMin !== undefined) this.defaultValueMin = options.valueMin; if (options.valueMax !== undefined) this.defaultValueMax = options.valueMax; if (options.cameraPosition !== undefined) cameraPosition = options.cameraPosition; if (cameraPosition !== undefined) { this.camera.setArmRotation(cameraPosition.horizontal, cameraPosition.vertical); this.camera.setArmLength(cameraPosition.distance); } else { this.camera.setArmRotation(1.0, 0.5); this.camera.setArmLength(1.7); } } this._setBackgroundColor(options && options.backgroundColor); this.setSize(this.width, this.height); // re-load the data if (this.dataTable) { this.setData(this.dataTable); } // start animation when option is true if (this.animationAutoStart && this.dataFilter) { this.animationStart(); } }; /** * Redraw the Graph. */ Graph3d.prototype.redraw = function() { if (this.dataPoints === undefined) { throw 'Error: graph data not initialized'; } this._resizeCanvas(); this._resizeCenter(); this._redrawSlider(); this._redrawClear(); this._redrawAxis(); if (this.style === Graph3d.STYLE.GRID || this.style === Graph3d.STYLE.SURFACE) { this._redrawDataGrid(); } else if (this.style === Graph3d.STYLE.LINE) { this._redrawDataLine(); } else if (this.style === Graph3d.STYLE.BAR || this.style === Graph3d.STYLE.BARCOLOR || this.style === Graph3d.STYLE.BARSIZE) { this._redrawDataBar(); } else { // style is DOT, DOTLINE, DOTCOLOR, DOTSIZE this._redrawDataDot(); } this._redrawInfo(); this._redrawLegend(); }; /** * Clear the canvas before redrawing */ Graph3d.prototype._redrawClear = function() { var canvas = this.frame.canvas; var ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height); }; /** * Redraw the legend showing the colors */ Graph3d.prototype._redrawLegend = function() { var y; if (this.style === Graph3d.STYLE.DOTCOLOR || this.style === Graph3d.STYLE.DOTSIZE) { var dotSize = this.frame.clientWidth * 0.02; var widthMin, widthMax; if (this.style === Graph3d.STYLE.DOTSIZE) { widthMin = dotSize / 2; // px widthMax = dotSize / 2 + dotSize * 2; // Todo: put this in one function } else { widthMin = 20; // px widthMax = 20; // px } var height = Math.max(this.frame.clientHeight * 0.25, 100); var top = this.margin; var right = this.frame.clientWidth - this.margin; var left = right - widthMax; var bottom = top + height; } var canvas = this.frame.canvas; var ctx = canvas.getContext('2d'); ctx.lineWidth = 1; ctx.font = '14px arial'; // TODO: put in options if (this.style === Graph3d.STYLE.DOTCOLOR) { // draw the color bar var ymin = 0; var ymax = height; // Todo: make height customizable for (y = ymin; y < ymax; y++) { var f = (y - ymin) / (ymax - ymin); //var width = (dotSize / 2 + (1-f) * dotSize * 2); // Todo: put this in one function var hue = f * 240; var color = this._hsv2rgb(hue, 1, 1); ctx.strokeStyle = color; ctx.beginPath(); ctx.moveTo(left, top + y); ctx.lineTo(right, top + y); ctx.stroke(); } ctx.strokeStyle = this.colorAxis; ctx.strokeRect(left, top, widthMax, height); } if (this.style === Graph3d.STYLE.DOTSIZE) { // draw border around color bar ctx.strokeStyle = this.colorAxis; ctx.fillStyle = this.colorDot; ctx.beginPath(); ctx.moveTo(left, top); ctx.lineTo(right, top); ctx.lineTo(right - widthMax + widthMin, bottom); ctx.lineTo(left, bottom); ctx.closePath(); ctx.fill(); ctx.stroke(); } if (this.style === Graph3d.STYLE.DOTCOLOR || this.style === Graph3d.STYLE.DOTSIZE) { // print values along the color bar var gridLineLen = 5; // px var step = new StepNumber(this.valueMin, this.valueMax, (this.valueMax-this.valueMin)/5, true); step.start(); if (step.getCurrent() < this.valueMin) { step.next(); } while (!step.end()) { y = bottom - (step.getCurrent() - this.valueMin) / (this.valueMax - this.valueMin) * height; ctx.beginPath(); ctx.moveTo(left - gridLineLen, y); ctx.lineTo(left, y); ctx.stroke(); ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; ctx.fillStyle = this.colorAxis; ctx.fillText(step.getCurrent(), left - 2 * gridLineLen, y); step.next(); } ctx.textAlign = 'right'; ctx.textBaseline = 'top'; var label = this.legendLabel; ctx.fillText(label, right, bottom + this.margin); } }; /** * Redraw the filter */ Graph3d.prototype._redrawFilter = function() { this.frame.filter.innerHTML = ''; if (this.dataFilter) { var options = { 'visible': this.showAnimationControls }; var slider = new Slider(this.frame.filter, options); this.frame.filter.slider = slider; // TODO: css here is not nice here... this.frame.filter.style.padding = '10px'; //this.frame.filter.style.backgroundColor = '#EFEFEF'; slider.setValues(this.dataFilter.values); slider.setPlayInterval(this.animationInterval); // create an event handler var me = this; var onchange = function () { var index = slider.getIndex(); me.dataFilter.selectValue(index); me.dataPoints = me.dataFilter._getDataPoints(); me.redraw(); }; slider.setOnChangeCallback(onchange); } else { this.frame.filter.slider = undefined; } }; /** * Redraw the slider */ Graph3d.prototype._redrawSlider = function() { if ( this.frame.filter.slider !== undefined) { this.frame.filter.slider.redraw(); } }; /** * Redraw common information */ Graph3d.prototype._redrawInfo = function() { if (this.dataFilter) { var canvas = this.frame.canvas; var ctx = canvas.getContext('2d'); ctx.font = '14px arial'; // TODO: put in options ctx.lineStyle = 'gray'; ctx.fillStyle = 'gray'; ctx.textAlign = 'left'; ctx.textBaseline = 'top'; var x = this.margin; var y = this.margin; ctx.fillText(this.dataFilter.getLabel() + ': ' + this.dataFilter.getSelectedValue(), x, y); } }; /** * Redraw the axis */ Graph3d.prototype._redrawAxis = function() { var canvas = this.frame.canvas, ctx = canvas.getContext('2d'), from, to, step, prettyStep, text, xText, yText, zText, offset, xOffset, yOffset, xMin2d, xMax2d; // TODO: get the actual rendered style of the containerElement //ctx.font = this.containerElement.style.font; ctx.font = 24 / this.camera.getArmLength() + 'px arial'; // calculate the length for the short grid lines var gridLenX = 0.025 / this.scale.x; var gridLenY = 0.025 / this.scale.y; var textMargin = 5 / this.camera.getArmLength(); // px var armAngle = this.camera.getArmRotation().horizontal; // draw x-grid lines ctx.lineWidth = 1; prettyStep = (this.defaultXStep === undefined); step = new StepNumber(this.xMin, this.xMax, this.xStep, prettyStep); step.start(); if (step.getCurrent() < this.xMin) { step.next(); } while (!step.end()) { var x = step.getCurrent(); if (this.showGrid) { from = this._convert3Dto2D(new Point3d(x, this.yMin, this.zMin)); to = this._convert3Dto2D(new Point3d(x, this.yMax, this.zMin)); ctx.strokeStyle = this.colorGrid; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); } else { from = this._convert3Dto2D(new Point3d(x, this.yMin, this.zMin)); to = this._convert3Dto2D(new Point3d(x, this.yMin+gridLenX, this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); from = this._convert3Dto2D(new Point3d(x, this.yMax, this.zMin)); to = this._convert3Dto2D(new Point3d(x, this.yMax-gridLenX, this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); } yText = (Math.cos(armAngle) > 0) ? this.yMin : this.yMax; text = this._convert3Dto2D(new Point3d(x, yText, this.zMin)); if (Math.cos(armAngle * 2) > 0) { ctx.textAlign = 'center'; ctx.textBaseline = 'top'; text.y += textMargin; } else if (Math.sin(armAngle * 2) < 0){ ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; } else { ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; } ctx.fillStyle = this.colorAxis; ctx.fillText(' ' + step.getCurrent() + ' ', text.x, text.y); step.next(); } // draw y-grid lines ctx.lineWidth = 1; prettyStep = (this.defaultYStep === undefined); step = new StepNumber(this.yMin, this.yMax, this.yStep, prettyStep); step.start(); if (step.getCurrent() < this.yMin) { step.next(); } while (!step.end()) { if (this.showGrid) { from = this._convert3Dto2D(new Point3d(this.xMin, step.getCurrent(), this.zMin)); to = this._convert3Dto2D(new Point3d(this.xMax, step.getCurrent(), this.zMin)); ctx.strokeStyle = this.colorGrid; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); } else { from = this._convert3Dto2D(new Point3d(this.xMin, step.getCurrent(), this.zMin)); to = this._convert3Dto2D(new Point3d(this.xMin+gridLenY, step.getCurrent(), this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); from = this._convert3Dto2D(new Point3d(this.xMax, step.getCurrent(), this.zMin)); to = this._convert3Dto2D(new Point3d(this.xMax-gridLenY, step.getCurrent(), this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); } xText = (Math.sin(armAngle ) > 0) ? this.xMin : this.xMax; text = this._convert3Dto2D(new Point3d(xText, step.getCurrent(), this.zMin)); if (Math.cos(armAngle * 2) < 0) { ctx.textAlign = 'center'; ctx.textBaseline = 'top'; text.y += textMargin; } else if (Math.sin(armAngle * 2) > 0){ ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; } else { ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; } ctx.fillStyle = this.colorAxis; ctx.fillText(' ' + step.getCurrent() + ' ', text.x, text.y); step.next(); } // draw z-grid lines and axis ctx.lineWidth = 1; prettyStep = (this.defaultZStep === undefined); step = new StepNumber(this.zMin, this.zMax, this.zStep, prettyStep); step.start(); if (step.getCurrent() < this.zMin) { step.next(); } xText = (Math.cos(armAngle ) > 0) ? this.xMin : this.xMax; yText = (Math.sin(armAngle ) < 0) ? this.yMin : this.yMax; while (!step.end()) { // TODO: make z-grid lines really 3d? from = this._convert3Dto2D(new Point3d(xText, yText, step.getCurrent())); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(from.x - textMargin, from.y); ctx.stroke(); ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; ctx.fillStyle = this.colorAxis; ctx.fillText(step.getCurrent() + ' ', from.x - 5, from.y); step.next(); } ctx.lineWidth = 1; from = this._convert3Dto2D(new Point3d(xText, yText, this.zMin)); to = this._convert3Dto2D(new Point3d(xText, yText, this.zMax)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); // draw x-axis ctx.lineWidth = 1; // line at yMin xMin2d = this._convert3Dto2D(new Point3d(this.xMin, this.yMin, this.zMin)); xMax2d = this._convert3Dto2D(new Point3d(this.xMax, this.yMin, this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(xMin2d.x, xMin2d.y); ctx.lineTo(xMax2d.x, xMax2d.y); ctx.stroke(); // line at ymax xMin2d = this._convert3Dto2D(new Point3d(this.xMin, this.yMax, this.zMin)); xMax2d = this._convert3Dto2D(new Point3d(this.xMax, this.yMax, this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(xMin2d.x, xMin2d.y); ctx.lineTo(xMax2d.x, xMax2d.y); ctx.stroke(); // draw y-axis ctx.lineWidth = 1; // line at xMin from = this._convert3Dto2D(new Point3d(this.xMin, this.yMin, this.zMin)); to = this._convert3Dto2D(new Point3d(this.xMin, this.yMax, this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); // line at xMax from = this._convert3Dto2D(new Point3d(this.xMax, this.yMin, this.zMin)); to = this._convert3Dto2D(new Point3d(this.xMax, this.yMax, this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); // draw x-label var xLabel = this.xLabel; if (xLabel.length > 0) { yOffset = 0.1 / this.scale.y; xText = (this.xMin + this.xMax) / 2; yText = (Math.cos(armAngle) > 0) ? this.yMin - yOffset: this.yMax + yOffset; text = this._convert3Dto2D(new Point3d(xText, yText, this.zMin)); if (Math.cos(armAngle * 2) > 0) { ctx.textAlign = 'center'; ctx.textBaseline = 'top'; } else if (Math.sin(armAngle * 2) < 0){ ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; } else { ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; } ctx.fillStyle = this.colorAxis; ctx.fillText(xLabel, text.x, text.y); } // draw y-label var yLabel = this.yLabel; if (yLabel.length > 0) { xOffset = 0.1 / this.scale.x; xText = (Math.sin(armAngle ) > 0) ? this.xMin - xOffset : this.xMax + xOffset; yText = (this.yMin + this.yMax) / 2; text = this._convert3Dto2D(new Point3d(xText, yText, this.zMin)); if (Math.cos(armAngle * 2) < 0) { ctx.textAlign = 'center'; ctx.textBaseline = 'top'; } else if (Math.sin(armAngle * 2) > 0){ ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; } else { ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; } ctx.fillStyle = this.colorAxis; ctx.fillText(yLabel, text.x, text.y); } // draw z-label var zLabel = this.zLabel; if (zLabel.length > 0) { offset = 30; // pixels. // TODO: relate to the max width of the values on the z axis? xText = (Math.cos(armAngle ) > 0) ? this.xMin : this.xMax; yText = (Math.sin(armAngle ) < 0) ? this.yMin : this.yMax; zText = (this.zMin + this.zMax) / 2; text = this._convert3Dto2D(new Point3d(xText, yText, zText)); ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; ctx.fillStyle = this.colorAxis; ctx.fillText(zLabel, text.x - offset, text.y); } }; /** * Calculate the color based on the given value. * @param {Number} H Hue, a value be between 0 and 360 * @param {Number} S Saturation, a value between 0 and 1 * @param {Number} V Value, a value between 0 and 1 */ Graph3d.prototype._hsv2rgb = function(H, S, V) { var R, G, B, C, Hi, X; C = V * S; Hi = Math.floor(H/60); // hi = 0,1,2,3,4,5 X = C * (1 - Math.abs(((H/60) % 2) - 1)); switch (Hi) { case 0: R = C; G = X; B = 0; break; case 1: R = X; G = C; B = 0; break; case 2: R = 0; G = C; B = X; break; case 3: R = 0; G = X; B = C; break; case 4: R = X; G = 0; B = C; break; case 5: R = C; G = 0; B = X; break; default: R = 0; G = 0; B = 0; break; } return 'RGB(' + parseInt(R*255) + ',' + parseInt(G*255) + ',' + parseInt(B*255) + ')'; }; /** * Draw all datapoints as a grid * This function can be used when the style is 'grid' */ Graph3d.prototype._redrawDataGrid = function() { var canvas = this.frame.canvas, ctx = canvas.getContext('2d'), point, right, top, cross, i, topSideVisible, fillStyle, strokeStyle, lineWidth, h, s, v, zAvg; if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? // calculate the translations and screen position of all points for (i = 0; i < this.dataPoints.length; i++) { var trans = this._convertPointToTranslation(this.dataPoints[i].point); var screen = this._convertTranslationToScreen(trans); this.dataPoints[i].trans = trans; this.dataPoints[i].screen = screen; // calculate the translation of the point at the bottom (needed for sorting) var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom); this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z; } // sort the points on depth of their (x,y) position (not on z) var sortDepth = function (a, b) { return b.dist - a.dist; }; this.dataPoints.sort(sortDepth); if (this.style === Graph3d.STYLE.SURFACE) { for (i = 0; i < this.dataPoints.length; i++) { point = this.dataPoints[i]; right = this.dataPoints[i].pointRight; top = this.dataPoints[i].pointTop; cross = this.dataPoints[i].pointCross; if (point !== undefined && right !== undefined && top !== undefined && cross !== undefined) { if (this.showGrayBottom || this.showShadow) { // calculate the cross product of the two vectors from center // to left and right, in order to know whether we are looking at the // bottom or at the top side. We can also use the cross product // for calculating light intensity var aDiff = Point3d.subtract(cross.trans, point.trans); var bDiff = Point3d.subtract(top.trans, right.trans); var crossproduct = Point3d.crossProduct(aDiff, bDiff); var len = crossproduct.length(); // FIXME: there is a bug with determining the surface side (shadow or colored) topSideVisible = (crossproduct.z > 0); } else { topSideVisible = true; } if (topSideVisible) { // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 zAvg = (point.point.z + right.point.z + top.point.z + cross.point.z) / 4; h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240; s = 1; // saturation if (this.showShadow) { v = Math.min(1 + (crossproduct.x / len) / 2, 1); // value. TODO: scale fillStyle = this._hsv2rgb(h, s, v); strokeStyle = fillStyle; } else { v = 1; fillStyle = this._hsv2rgb(h, s, v); strokeStyle = this.colorAxis; } } else { fillStyle = 'gray'; strokeStyle = this.colorAxis; } lineWidth = 0.5; ctx.lineWidth = lineWidth; ctx.fillStyle = fillStyle; ctx.strokeStyle = strokeStyle; ctx.beginPath(); ctx.moveTo(point.screen.x, point.screen.y); ctx.lineTo(right.screen.x, right.screen.y); ctx.lineTo(cross.screen.x, cross.screen.y); ctx.lineTo(top.screen.x, top.screen.y); ctx.closePath(); ctx.fill(); ctx.stroke(); } } } else { // grid style for (i = 0; i < this.dataPoints.length; i++) { point = this.dataPoints[i]; right = this.dataPoints[i].pointRight; top = this.dataPoints[i].pointTop; if (point !== undefined) { if (this.showPerspective) { lineWidth = 2 / -point.trans.z; } else { lineWidth = 2 * -(this.eye.z / this.camera.getArmLength()); } } if (point !== undefined && right !== undefined) { // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 zAvg = (point.point.z + right.point.z) / 2; h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240; ctx.lineWidth = lineWidth; ctx.strokeStyle = this._hsv2rgb(h, 1, 1); ctx.beginPath(); ctx.moveTo(point.screen.x, point.screen.y); ctx.lineTo(right.screen.x, right.screen.y); ctx.stroke(); } if (point !== undefined && top !== undefined) { // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 zAvg = (point.point.z + top.point.z) / 2; h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240; ctx.lineWidth = lineWidth; ctx.strokeStyle = this._hsv2rgb(h, 1, 1); ctx.beginPath(); ctx.moveTo(point.screen.x, point.screen.y); ctx.lineTo(top.screen.x, top.screen.y); ctx.stroke(); } } } }; /** * Draw all datapoints as dots. * This function can be used when the style is 'dot' or 'dot-line' */ Graph3d.prototype._redrawDataDot = function() { var canvas = this.frame.canvas; var ctx = canvas.getContext('2d'); var i; if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? // calculate the translations of all points for (i = 0; i < this.dataPoints.length; i++) { var trans = this._convertPointToTranslation(this.dataPoints[i].point); var screen = this._convertTranslationToScreen(trans); this.dataPoints[i].trans = trans; this.dataPoints[i].screen = screen; // calculate the distance from the point at the bottom to the camera var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom); this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z; } // order the translated points by depth var sortDepth = function (a, b) { return b.dist - a.dist; }; this.dataPoints.sort(sortDepth); // draw the datapoints as colored circles var dotSize = this.frame.clientWidth * 0.02; // px for (i = 0; i < this.dataPoints.length; i++) { var point = this.dataPoints[i]; if (this.style === Graph3d.STYLE.DOTLINE) { // draw a vertical line from the bottom to the graph value //var from = this._convert3Dto2D(new Point3d(point.point.x, point.point.y, this.zMin)); var from = this._convert3Dto2D(point.bottom); ctx.lineWidth = 1; ctx.strokeStyle = this.colorGrid; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(point.screen.x, point.screen.y); ctx.stroke(); } // calculate radius for the circle var size; if (this.style === Graph3d.STYLE.DOTSIZE) { size = dotSize/2 + 2*dotSize * (point.point.value - this.valueMin) / (this.valueMax - this.valueMin); } else { size = dotSize; } var radius; if (this.showPerspective) { radius = size / -point.trans.z; } else { radius = size * -(this.eye.z / this.camera.getArmLength()); } if (radius < 0) { radius = 0; } var hue, color, borderColor; if (this.style === Graph3d.STYLE.DOTCOLOR ) { // calculate the color based on the value hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240; color = this._hsv2rgb(hue, 1, 1); borderColor = this._hsv2rgb(hue, 1, 0.8); } else if (this.style === Graph3d.STYLE.DOTSIZE) { color = this.colorDot; borderColor = this.colorDotBorder; } else { // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240; color = this._hsv2rgb(hue, 1, 1); borderColor = this._hsv2rgb(hue, 1, 0.8); } // draw the circle ctx.lineWidth = 1.0; ctx.strokeStyle = borderColor; ctx.fillStyle = color; ctx.beginPath(); ctx.arc(point.screen.x, point.screen.y, radius, 0, Math.PI*2, true); ctx.fill(); ctx.stroke(); } }; /** * Draw all datapoints as bars. * This function can be used when the style is 'bar', 'bar-color', or 'bar-size' */ Graph3d.prototype._redrawDataBar = function() { var canvas = this.frame.canvas; var ctx = canvas.getContext('2d'); var i, j, surface, corners; if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? // calculate the translations of all points for (i = 0; i < this.dataPoints.length; i++) { var trans = this._convertPointToTranslation(this.dataPoints[i].point); var screen = this._convertTranslationToScreen(trans); this.dataPoints[i].trans = trans; this.dataPoints[i].screen = screen; // calculate the distance from the point at the bottom to the camera var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom); this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z; } // order the translated points by depth var sortDepth = function (a, b) { return b.dist - a.dist; }; this.dataPoints.sort(sortDepth); // draw the datapoints as bars var xWidth = this.xBarWidth / 2; var yWidth = this.yBarWidth / 2; for (i = 0; i < this.dataPoints.length; i++) { var point = this.dataPoints[i]; // determine color var hue, color, borderColor; if (this.style === Graph3d.STYLE.BARCOLOR ) { // calculate the color based on the value hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240; color = this._hsv2rgb(hue, 1, 1); borderColor = this._hsv2rgb(hue, 1, 0.8); } else if (this.style === Graph3d.STYLE.BARSIZE) { color = this.colorDot; borderColor = this.colorDotBorder; } else { // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240; color = this._hsv2rgb(hue, 1, 1); borderColor = this._hsv2rgb(hue, 1, 0.8); } // calculate size for the bar if (this.style === Graph3d.STYLE.BARSIZE) { xWidth = (this.xBarWidth / 2) * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2); yWidth = (this.yBarWidth / 2) * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2); } // calculate all corner points var me = this; var point3d = point.point; var top = [ {point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, point3d.z)}, {point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, point3d.z)}, {point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, point3d.z)}, {point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, point3d.z)} ]; var bottom = [ {point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, this.zMin)}, {point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, this.zMin)}, {point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, this.zMin)}, {point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, this.zMin)} ]; // calculate screen location of the points top.forEach(function (obj) { obj.screen = me._convert3Dto2D(obj.point); }); bottom.forEach(function (obj) { obj.screen = me._convert3Dto2D(obj.point); }); // create five sides, calculate both corner points and center points var surfaces = [ {corners: top, center: Point3d.avg(bottom[0].point, bottom[2].point)}, {corners: [top[0], top[1], bottom[1], bottom[0]], center: Point3d.avg(bottom[1].point, bottom[0].point)}, {corners: [top[1], top[2], bottom[2], bottom[1]], center: Point3d.avg(bottom[2].point, bottom[1].point)}, {corners: [top[2], top[3], bottom[3], bottom[2]], center: Point3d.avg(bottom[3].point, bottom[2].point)}, {corners: [top[3], top[0], bottom[0], bottom[3]], center: Point3d.avg(bottom[0].point, bottom[3].point)} ]; point.surfaces = surfaces; // calculate the distance of each of the surface centers to the camera for (j = 0; j < surfaces.length; j++) { surface = surfaces[j]; var transCenter = this._convertPointToTranslation(surface.center); surface.dist = this.showPerspective ? transCenter.length() : -transCenter.z; // TODO: this dept calculation doesn't work 100% of the cases due to perspective, // but the current solution is fast/simple and works in 99.9% of all cases // the issue is visible in example 14, with graph.setCameraPosition({horizontal: 2.97, vertical: 0.5, distance: 0.9}) } // order the surfaces by their (translated) depth surfaces.sort(function (a, b) { var diff = b.dist - a.dist; if (diff) return diff; // if equal depth, sort the top surface last if (a.corners === top) return 1; if (b.corners === top) return -1; // both are equal return 0; }); // draw the ordered surfaces ctx.lineWidth = 1; ctx.strokeStyle = borderColor; ctx.fillStyle = color; // NOTE: we start at j=2 instead of j=0 as we don't need to draw the two surfaces at the backside for (j = 2; j < surfaces.length; j++) { surface = surfaces[j]; corners = surface.corners; ctx.beginPath(); ctx.moveTo(corners[3].screen.x, corners[3].screen.y); ctx.lineTo(corners[0].screen.x, corners[0].screen.y); ctx.lineTo(corners[1].screen.x, corners[1].screen.y); ctx.lineTo(corners[2].screen.x, corners[2].screen.y); ctx.lineTo(corners[3].screen.x, corners[3].screen.y); ctx.fill(); ctx.stroke(); } } }; /** * Draw a line through all datapoints. * This function can be used when the style is 'line' */ Graph3d.prototype._redrawDataLine = function() { var canvas = this.frame.canvas, ctx = canvas.getContext('2d'), point, i; if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? // calculate the translations of all points for (i = 0; i < this.dataPoints.length; i++) { var trans = this._convertPointToTranslation(this.dataPoints[i].point); var screen = this._convertTranslationToScreen(trans); this.dataPoints[i].trans = trans; this.dataPoints[i].screen = screen; } // start the line if (this.dataPoints.length > 0) { point = this.dataPoints[0]; ctx.lineWidth = 1; // TODO: make customizable ctx.strokeStyle = 'blue'; // TODO: make customizable ctx.beginPath(); ctx.moveTo(point.screen.x, point.screen.y); } // draw the datapoints as colored circles for (i = 1; i < this.dataPoints.length; i++) { point = this.dataPoints[i]; ctx.lineTo(point.screen.x, point.screen.y); } // finish the line if (this.dataPoints.length > 0) { ctx.stroke(); } }; /** * Start a moving operation inside the provided parent element * @param {Event} event The event that occurred (required for * retrieving the mouse position) */ Graph3d.prototype._onMouseDown = function(event) { event = event || window.event; // check if mouse is still down (may be up when focus is lost for example // in an iframe) if (this.leftButtonDown) { this._onMouseUp(event); } // only react on left mouse button down this.leftButtonDown = event.which ? (event.which === 1) : (event.button === 1); if (!this.leftButtonDown && !this.touchDown) return; // get mouse position (different code for IE and all other browsers) this.startMouseX = getMouseX(event); this.startMouseY = getMouseY(event); this.startStart = new Date(this.start); this.startEnd = new Date(this.end); this.startArmRotation = this.camera.getArmRotation(); this.frame.style.cursor = 'move'; // add event listeners to handle moving the contents // we store the function onmousemove and onmouseup in the graph, so we can // remove the eventlisteners lateron in the function mouseUp() var me = this; this.onmousemove = function (event) {me._onMouseMove(event);}; this.onmouseup = function (event) {me._onMouseUp(event);}; util.addEventListener(document, 'mousemove', me.onmousemove); util.addEventListener(document, 'mouseup', me.onmouseup); util.preventDefault(event); }; /** * Perform moving operating. * This function activated from within the funcion Graph.mouseDown(). * @param {Event} event Well, eehh, the event */ Graph3d.prototype._onMouseMove = function (event) { event = event || window.event; // calculate change in mouse position var diffX = parseFloat(getMouseX(event)) - this.startMouseX; var diffY = parseFloat(getMouseY(event)) - this.startMouseY; var horizontalNew = this.startArmRotation.horizontal + diffX / 200; var verticalNew = this.startArmRotation.vertical + diffY / 200; var snapAngle = 4; // degrees var snapValue = Math.sin(snapAngle / 360 * 2 * Math.PI); // snap horizontally to nice angles at 0pi, 0.5pi, 1pi, 1.5pi, etc... // the -0.001 is to take care that the vertical axis is always drawn at the left front corner if (Math.abs(Math.sin(horizontalNew)) < snapValue) { horizontalNew = Math.round((horizontalNew / Math.PI)) * Math.PI - 0.001; } if (Math.abs(Math.cos(horizontalNew)) < snapValue) { horizontalNew = (Math.round((horizontalNew/ Math.PI - 0.5)) + 0.5) * Math.PI - 0.001; } // snap vertically to nice angles if (Math.abs(Math.sin(verticalNew)) < snapValue) { verticalNew = Math.round((verticalNew / Math.PI)) * Math.PI; } if (Math.abs(Math.cos(verticalNew)) < snapValue) { verticalNew = (Math.round((verticalNew/ Math.PI - 0.5)) + 0.5) * Math.PI; } this.camera.setArmRotation(horizontalNew, verticalNew); this.redraw(); // fire a cameraPositionChange event var parameters = this.getCameraPosition(); this.emit('cameraPositionChange', parameters); util.preventDefault(event); }; /** * Stop moving operating. * This function activated from within the funcion Graph.mouseDown(). * @param {event} event The event */ Graph3d.prototype._onMouseUp = function (event) { this.frame.style.cursor = 'auto'; this.leftButtonDown = false; // remove event listeners here util.removeEventListener(document, 'mousemove', this.onmousemove); util.removeEventListener(document, 'mouseup', this.onmouseup); util.preventDefault(event); }; /** * After having moved the mouse, a tooltip should pop up when the mouse is resting on a data point * @param {Event} event A mouse move event */ Graph3d.prototype._onTooltip = function (event) { var delay = 300; // ms var mouseX = getMouseX(event) - util.getAbsoluteLeft(this.frame); var mouseY = getMouseY(event) - util.getAbsoluteTop(this.frame); if (!this.showTooltip) { return; } if (this.tooltipTimeout) { clearTimeout(this.tooltipTimeout); } // (delayed) display of a tooltip only if no mouse button is down if (this.leftButtonDown) { this._hideTooltip(); return; } if (this.tooltip && this.tooltip.dataPoint) { // tooltip is currently visible var dataPoint = this._dataPointFromXY(mouseX, mouseY); if (dataPoint !== this.tooltip.dataPoint) { // datapoint changed if (dataPoint) { this._showTooltip(dataPoint); } else { this._hideTooltip(); } } } else { // tooltip is currently not visible var me = this; this.tooltipTimeout = setTimeout(function () { me.tooltipTimeout = null; // show a tooltip if we have a data point var dataPoint = me._dataPointFromXY(mouseX, mouseY); if (dataPoint) { me._showTooltip(dataPoint); } }, delay); } }; /** * Event handler for touchstart event on mobile devices */ Graph3d.prototype._onTouchStart = function(event) { this.touchDown = true; var me = this; this.ontouchmove = function (event) {me._onTouchMove(event);}; this.ontouchend = function (event) {me._onTouchEnd(event);}; util.addEventListener(document, 'touchmove', me.ontouchmove); util.addEventListener(document, 'touchend', me.ontouchend); this._onMouseDown(event); }; /** * Event handler for touchmove event on mobile devices */ Graph3d.prototype._onTouchMove = function(event) { this._onMouseMove(event); }; /** * Event handler for touchend event on mobile devices */ Graph3d.prototype._onTouchEnd = function(event) { this.touchDown = false; util.removeEventListener(document, 'touchmove', this.ontouchmove); util.removeEventListener(document, 'touchend', this.ontouchend); this._onMouseUp(event); }; /** * Event handler for mouse wheel event, used to zoom the graph * Code from http://adomas.org/javascript-mouse-wheel/ * @param {event} event The event */ Graph3d.prototype._onWheel = function(event) { if (!event) /* For IE. */ event = window.event; // retrieve delta var delta = 0; if (event.wheelDelta) { /* IE/Opera. */ delta = event.wheelDelta/120; } else if (event.detail) { /* Mozilla case. */ // In Mozilla, sign of delta is different than in IE. // Also, delta is multiple of 3. delta = -event.detail/3; } // If delta is nonzero, handle it. // Basically, delta is now positive if wheel was scrolled up, // and negative, if wheel was scrolled down. if (delta) { var oldLength = this.camera.getArmLength(); var newLength = oldLength * (1 - delta / 10); this.camera.setArmLength(newLength); this.redraw(); this._hideTooltip(); } // fire a cameraPositionChange event var parameters = this.getCameraPosition(); this.emit('cameraPositionChange', parameters); // Prevent default actions caused by mouse wheel. // That might be ugly, but we handle scrolls somehow // anyway, so don't bother here.. util.preventDefault(event); }; /** * Test whether a point lies inside given 2D triangle * @param {Point2d} point * @param {Point2d[]} triangle * @return {boolean} Returns true if given point lies inside or on the edge of the triangle * @private */ Graph3d.prototype._insideTriangle = function (point, triangle) { var a = triangle[0], b = triangle[1], c = triangle[2]; function sign (x) { return x > 0 ? 1 : x < 0 ? -1 : 0; } var as = sign((b.x - a.x) * (point.y - a.y) - (b.y - a.y) * (point.x - a.x)); var bs = sign((c.x - b.x) * (point.y - b.y) - (c.y - b.y) * (point.x - b.x)); var cs = sign((a.x - c.x) * (point.y - c.y) - (a.y - c.y) * (point.x - c.x)); // each of the three signs must be either equal to each other or zero return (as == 0 || bs == 0 || as == bs) && (bs == 0 || cs == 0 || bs == cs) && (as == 0 || cs == 0 || as == cs); }; /** * Find a data point close to given screen position (x, y) * @param {Number} x * @param {Number} y * @return {Object | null} The closest data point or null if not close to any data point * @private */ Graph3d.prototype._dataPointFromXY = function (x, y) { var i, distMax = 100, // px dataPoint = null, closestDataPoint = null, closestDist = null, center = new Point2d(x, y); if (this.style === Graph3d.STYLE.BAR || this.style === Graph3d.STYLE.BARCOLOR || this.style === Graph3d.STYLE.BARSIZE) { // the data points are ordered from far away to closest for (i = this.dataPoints.length - 1; i >= 0; i--) { dataPoint = this.dataPoints[i]; var surfaces = dataPoint.surfaces; if (surfaces) { for (var s = surfaces.length - 1; s >= 0; s--) { // split each surface in two triangles, and see if the center point is inside one of these var surface = surfaces[s]; var corners = surface.corners; var triangle1 = [corners[0].screen, corners[1].screen, corners[2].screen]; var triangle2 = [corners[2].screen, corners[3].screen, corners[0].screen]; if (this._insideTriangle(center, triangle1) || this._insideTriangle(center, triangle2)) { // return immediately at the first hit return dataPoint; } } } } } else { // find the closest data point, using distance to the center of the point on 2d screen for (i = 0; i < this.dataPoints.length; i++) { dataPoint = this.dataPoints[i]; var point = dataPoint.screen; if (point) { var distX = Math.abs(x - point.x); var distY = Math.abs(y - point.y); var dist = Math.sqrt(distX * distX + distY * distY); if ((closestDist === null || dist < closestDist) && dist < distMax) { closestDist = dist; closestDataPoint = dataPoint; } } } } return closestDataPoint; }; /** * Display a tooltip for given data point * @param {Object} dataPoint * @private */ Graph3d.prototype._showTooltip = function (dataPoint) { var content, line, dot; if (!this.tooltip) { content = document.createElement('div'); content.style.position = 'absolute'; content.style.padding = '10px'; content.style.border = '1px solid #4d4d4d'; content.style.color = '#1a1a1a'; content.style.background = 'rgba(255,255,255,0.7)'; content.style.borderRadius = '2px'; content.style.boxShadow = '5px 5px 10px rgba(128,128,128,0.5)'; line = document.createElement('div'); line.style.position = 'absolute'; line.style.height = '40px'; line.style.width = '0'; line.style.borderLeft = '1px solid #4d4d4d'; dot = document.createElement('div'); dot.style.position = 'absolute'; dot.style.height = '0'; dot.style.width = '0'; dot.style.border = '5px solid #4d4d4d'; dot.style.borderRadius = '5px'; this.tooltip = { dataPoint: null, dom: { content: content, line: line, dot: dot } }; } else { content = this.tooltip.dom.content; line = this.tooltip.dom.line; dot = this.tooltip.dom.dot; } this._hideTooltip(); this.tooltip.dataPoint = dataPoint; if (typeof this.showTooltip === 'function') { content.innerHTML = this.showTooltip(dataPoint.point); } else { content.innerHTML = '<table>' + '<tr><td>x:</td><td>' + dataPoint.point.x + '</td></tr>' + '<tr><td>y:</td><td>' + dataPoint.point.y + '</td></tr>' + '<tr><td>z:</td><td>' + dataPoint.point.z + '</td></tr>' + '</table>'; } content.style.left = '0'; content.style.top = '0'; this.frame.appendChild(content); this.frame.appendChild(line); this.frame.appendChild(dot); // calculate sizes var contentWidth = content.offsetWidth; var contentHeight = content.offsetHeight; var lineHeight = line.offsetHeight; var dotWidth = dot.offsetWidth; var dotHeight = dot.offsetHeight; var left = dataPoint.screen.x - contentWidth / 2; left = Math.min(Math.max(left, 10), this.frame.clientWidth - 10 - contentWidth); line.style.left = dataPoint.screen.x + 'px'; line.style.top = (dataPoint.screen.y - lineHeight) + 'px'; content.style.left = left + 'px'; content.style.top = (dataPoint.screen.y - lineHeight - contentHeight) + 'px'; dot.style.left = (dataPoint.screen.x - dotWidth / 2) + 'px'; dot.style.top = (dataPoint.screen.y - dotHeight / 2) + 'px'; }; /** * Hide the tooltip when displayed * @private */ Graph3d.prototype._hideTooltip = function () { if (this.tooltip) { this.tooltip.dataPoint = null; for (var prop in this.tooltip.dom) { if (this.tooltip.dom.hasOwnProperty(prop)) { var elem = this.tooltip.dom[prop]; if (elem && elem.parentNode) { elem.parentNode.removeChild(elem); } } } } }; /**--------------------------------------------------------------------------**/ /** * Get the horizontal mouse position from a mouse event * @param {Event} event * @return {Number} mouse x */ getMouseX = function(event) { if ('clientX' in event) return event.clientX; return event.targetTouches[0] && event.targetTouches[0].clientX || 0; }; /** * Get the vertical mouse position from a mouse event * @param {Event} event * @return {Number} mouse y */ getMouseY = function(event) { if ('clientY' in event) return event.clientY; return event.targetTouches[0] && event.targetTouches[0].clientY || 0; }; module.exports = Graph3d; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { var Point3d = __webpack_require__(9); /** * @class Camera * The camera is mounted on a (virtual) camera arm. The camera arm can rotate * The camera is always looking in the direction of the origin of the arm. * This way, the camera always rotates around one fixed point, the location * of the camera arm. * * Documentation: * http://en.wikipedia.org/wiki/3D_projection */ Camera = function () { this.armLocation = new Point3d(); this.armRotation = {}; this.armRotation.horizontal = 0; this.armRotation.vertical = 0; this.armLength = 1.7; this.cameraLocation = new Point3d(); this.cameraRotation = new Point3d(0.5*Math.PI, 0, 0); this.calculateCameraOrientation(); }; /** * Set the location (origin) of the arm * @param {Number} x Normalized value of x * @param {Number} y Normalized value of y * @param {Number} z Normalized value of z */ Camera.prototype.setArmLocation = function(x, y, z) { this.armLocation.x = x; this.armLocation.y = y; this.armLocation.z = z; this.calculateCameraOrientation(); }; /** * Set the rotation of the camera arm * @param {Number} horizontal The horizontal rotation, between 0 and 2*PI. * Optional, can be left undefined. * @param {Number} vertical The vertical rotation, between 0 and 0.5*PI * if vertical=0.5*PI, the graph is shown from the * top. Optional, can be left undefined. */ Camera.prototype.setArmRotation = function(horizontal, vertical) { if (horizontal !== undefined) { this.armRotation.horizontal = horizontal; } if (vertical !== undefined) { this.armRotation.vertical = vertical; if (this.armRotation.vertical < 0) this.armRotation.vertical = 0; if (this.armRotation.vertical > 0.5*Math.PI) this.armRotation.vertical = 0.5*Math.PI; } if (horizontal !== undefined || vertical !== undefined) { this.calculateCameraOrientation(); } }; /** * Retrieve the current arm rotation * @return {object} An object with parameters horizontal and vertical */ Camera.prototype.getArmRotation = function() { var rot = {}; rot.horizontal = this.armRotation.horizontal; rot.vertical = this.armRotation.vertical; return rot; }; /** * Set the (normalized) length of the camera arm. * @param {Number} length A length between 0.71 and 5.0 */ Camera.prototype.setArmLength = function(length) { if (length === undefined) return; this.armLength = length; // Radius must be larger than the corner of the graph, // which has a distance of sqrt(0.5^2+0.5^2) = 0.71 from the center of the // graph if (this.armLength < 0.71) this.armLength = 0.71; if (this.armLength > 5.0) this.armLength = 5.0; this.calculateCameraOrientation(); }; /** * Retrieve the arm length * @return {Number} length */ Camera.prototype.getArmLength = function() { return this.armLength; }; /** * Retrieve the camera location * @return {Point3d} cameraLocation */ Camera.prototype.getCameraLocation = function() { return this.cameraLocation; }; /** * Retrieve the camera rotation * @return {Point3d} cameraRotation */ Camera.prototype.getCameraRotation = function() { return this.cameraRotation; }; /** * Calculate the location and rotation of the camera based on the * position and orientation of the camera arm */ Camera.prototype.calculateCameraOrientation = function() { // calculate location of the camera this.cameraLocation.x = this.armLocation.x - this.armLength * Math.sin(this.armRotation.horizontal) * Math.cos(this.armRotation.vertical); this.cameraLocation.y = this.armLocation.y - this.armLength * Math.cos(this.armRotation.horizontal) * Math.cos(this.armRotation.vertical); this.cameraLocation.z = this.armLocation.z + this.armLength * Math.sin(this.armRotation.vertical); // calculate rotation of the camera this.cameraRotation.x = Math.PI/2 - this.armRotation.vertical; this.cameraRotation.y = 0; this.cameraRotation.z = -this.armRotation.horizontal; }; module.exports = Camera; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { var DataView = __webpack_require__(4); /** * @class Filter * * @param {DataSet} data The google data table * @param {Number} column The index of the column to be filtered * @param {Graph} graph The graph */ function Filter (data, column, graph) { this.data = data; this.column = column; this.graph = graph; // the parent graph this.index = undefined; this.value = undefined; // read all distinct values and select the first one this.values = graph.getDistinctValues(data.get(), this.column); // sort both numeric and string values correctly this.values.sort(function (a, b) { return a > b ? 1 : a < b ? -1 : 0; }); if (this.values.length > 0) { this.selectValue(0); } // create an array with the filtered datapoints. this will be loaded afterwards this.dataPoints = []; this.loaded = false; this.onLoadCallback = undefined; if (graph.animationPreload) { this.loaded = false; this.loadInBackground(); } else { this.loaded = true; } }; /** * Return the label * @return {string} label */ Filter.prototype.isLoaded = function() { return this.loaded; }; /** * Return the loaded progress * @return {Number} percentage between 0 and 100 */ Filter.prototype.getLoadedProgress = function() { var len = this.values.length; var i = 0; while (this.dataPoints[i]) { i++; } return Math.round(i / len * 100); }; /** * Return the label * @return {string} label */ Filter.prototype.getLabel = function() { return this.graph.filterLabel; }; /** * Return the columnIndex of the filter * @return {Number} columnIndex */ Filter.prototype.getColumn = function() { return this.column; }; /** * Return the currently selected value. Returns undefined if there is no selection * @return {*} value */ Filter.prototype.getSelectedValue = function() { if (this.index === undefined) return undefined; return this.values[this.index]; }; /** * Retrieve all values of the filter * @return {Array} values */ Filter.prototype.getValues = function() { return this.values; }; /** * Retrieve one value of the filter * @param {Number} index * @return {*} value */ Filter.prototype.getValue = function(index) { if (index >= this.values.length) throw 'Error: index out of range'; return this.values[index]; }; /** * Retrieve the (filtered) dataPoints for the currently selected filter index * @param {Number} [index] (optional) * @return {Array} dataPoints */ Filter.prototype._getDataPoints = function(index) { if (index === undefined) index = this.index; if (index === undefined) return []; var dataPoints; if (this.dataPoints[index]) { dataPoints = this.dataPoints[index]; } else { var f = {}; f.column = this.column; f.value = this.values[index]; var dataView = new DataView(this.data,{filter: function (item) {return (item[f.column] == f.value);}}).get(); dataPoints = this.graph._getDataPoints(dataView); this.dataPoints[index] = dataPoints; } return dataPoints; }; /** * Set a callback function when the filter is fully loaded. */ Filter.prototype.setOnLoadCallback = function(callback) { this.onLoadCallback = callback; }; /** * Add a value to the list with available values for this filter * No double entries will be created. * @param {Number} index */ Filter.prototype.selectValue = function(index) { if (index >= this.values.length) throw 'Error: index out of range'; this.index = index; this.value = this.values[index]; }; /** * Load all filtered rows in the background one by one * Start this method without providing an index! */ Filter.prototype.loadInBackground = function(index) { if (index === undefined) index = 0; var frame = this.graph.frame; if (index < this.values.length) { var dataPointsTemp = this._getDataPoints(index); //this.graph.redrawInfo(); // TODO: not neat // create a progress box if (frame.progress === undefined) { frame.progress = document.createElement('DIV'); frame.progress.style.position = 'absolute'; frame.progress.style.color = 'gray'; frame.appendChild(frame.progress); } var progress = this.getLoadedProgress(); frame.progress.innerHTML = 'Loading animation... ' + progress + '%'; // TODO: this is no nice solution... frame.progress.style.bottom = 60 + 'px'; // TODO: use height of slider frame.progress.style.left = 10 + 'px'; var me = this; setTimeout(function() {me.loadInBackground(index+1);}, 10); this.loaded = false; } else { this.loaded = true; // remove the progress box if (frame.progress !== undefined) { frame.removeChild(frame.progress); frame.progress = undefined; } if (this.onLoadCallback) this.onLoadCallback(); } }; module.exports = Filter; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { /** * @prototype Point2d * @param {Number} [x] * @param {Number} [y] */ Point2d = function (x, y) { this.x = x !== undefined ? x : 0; this.y = y !== undefined ? y : 0; }; module.exports = Point2d; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { /** * @prototype Point3d * @param {Number} [x] * @param {Number} [y] * @param {Number} [z] */ function Point3d(x, y, z) { this.x = x !== undefined ? x : 0; this.y = y !== undefined ? y : 0; this.z = z !== undefined ? z : 0; }; /** * Subtract the two provided points, returns a-b * @param {Point3d} a * @param {Point3d} b * @return {Point3d} a-b */ Point3d.subtract = function(a, b) { var sub = new Point3d(); sub.x = a.x - b.x; sub.y = a.y - b.y; sub.z = a.z - b.z; return sub; }; /** * Add the two provided points, returns a+b * @param {Point3d} a * @param {Point3d} b * @return {Point3d} a+b */ Point3d.add = function(a, b) { var sum = new Point3d(); sum.x = a.x + b.x; sum.y = a.y + b.y; sum.z = a.z + b.z; return sum; }; /** * Calculate the average of two 3d points * @param {Point3d} a * @param {Point3d} b * @return {Point3d} The average, (a+b)/2 */ Point3d.avg = function(a, b) { return new Point3d( (a.x + b.x) / 2, (a.y + b.y) / 2, (a.z + b.z) / 2 ); }; /** * Calculate the cross product of the two provided points, returns axb * Documentation: http://en.wikipedia.org/wiki/Cross_product * @param {Point3d} a * @param {Point3d} b * @return {Point3d} cross product axb */ Point3d.crossProduct = function(a, b) { var crossproduct = new Point3d(); crossproduct.x = a.y * b.z - a.z * b.y; crossproduct.y = a.z * b.x - a.x * b.z; crossproduct.z = a.x * b.y - a.y * b.x; return crossproduct; }; /** * Rtrieve the length of the vector (or the distance from this point to the origin * @return {Number} length */ Point3d.prototype.length = function() { return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); }; module.exports = Point3d; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); /** * @constructor Slider * * An html slider control with start/stop/prev/next buttons * @param {Element} container The element where the slider will be created * @param {Object} options Available options: * {boolean} visible If true (default) the * slider is visible. */ function Slider(container, options) { if (container === undefined) { throw 'Error: No container element defined'; } this.container = container; this.visible = (options && options.visible != undefined) ? options.visible : true; if (this.visible) { this.frame = document.createElement('DIV'); //this.frame.style.backgroundColor = '#E5E5E5'; this.frame.style.width = '100%'; this.frame.style.position = 'relative'; this.container.appendChild(this.frame); this.frame.prev = document.createElement('INPUT'); this.frame.prev.type = 'BUTTON'; this.frame.prev.value = 'Prev'; this.frame.appendChild(this.frame.prev); this.frame.play = document.createElement('INPUT'); this.frame.play.type = 'BUTTON'; this.frame.play.value = 'Play'; this.frame.appendChild(this.frame.play); this.frame.next = document.createElement('INPUT'); this.frame.next.type = 'BUTTON'; this.frame.next.value = 'Next'; this.frame.appendChild(this.frame.next); this.frame.bar = document.createElement('INPUT'); this.frame.bar.type = 'BUTTON'; this.frame.bar.style.position = 'absolute'; this.frame.bar.style.border = '1px solid red'; this.frame.bar.style.width = '100px'; this.frame.bar.style.height = '6px'; this.frame.bar.style.borderRadius = '2px'; this.frame.bar.style.MozBorderRadius = '2px'; this.frame.bar.style.border = '1px solid #7F7F7F'; this.frame.bar.style.backgroundColor = '#E5E5E5'; this.frame.appendChild(this.frame.bar); this.frame.slide = document.createElement('INPUT'); this.frame.slide.type = 'BUTTON'; this.frame.slide.style.margin = '0px'; this.frame.slide.value = ' '; this.frame.slide.style.position = 'relative'; this.frame.slide.style.left = '-100px'; this.frame.appendChild(this.frame.slide); // create events var me = this; this.frame.slide.onmousedown = function (event) {me._onMouseDown(event);}; this.frame.prev.onclick = function (event) {me.prev(event);}; this.frame.play.onclick = function (event) {me.togglePlay(event);}; this.frame.next.onclick = function (event) {me.next(event);}; } this.onChangeCallback = undefined; this.values = []; this.index = undefined; this.playTimeout = undefined; this.playInterval = 1000; // milliseconds this.playLoop = true; } /** * Select the previous index */ Slider.prototype.prev = function() { var index = this.getIndex(); if (index > 0) { index--; this.setIndex(index); } }; /** * Select the next index */ Slider.prototype.next = function() { var index = this.getIndex(); if (index < this.values.length - 1) { index++; this.setIndex(index); } }; /** * Select the next index */ Slider.prototype.playNext = function() { var start = new Date(); var index = this.getIndex(); if (index < this.values.length - 1) { index++; this.setIndex(index); } else if (this.playLoop) { // jump to the start index = 0; this.setIndex(index); } var end = new Date(); var diff = (end - start); // calculate how much time it to to set the index and to execute the callback // function. var interval = Math.max(this.playInterval - diff, 0); // document.title = diff // TODO: cleanup var me = this; this.playTimeout = setTimeout(function() {me.playNext();}, interval); }; /** * Toggle start or stop playing */ Slider.prototype.togglePlay = function() { if (this.playTimeout === undefined) { this.play(); } else { this.stop(); } }; /** * Start playing */ Slider.prototype.play = function() { // Test whether already playing if (this.playTimeout) return; this.playNext(); if (this.frame) { this.frame.play.value = 'Stop'; } }; /** * Stop playing */ Slider.prototype.stop = function() { clearInterval(this.playTimeout); this.playTimeout = undefined; if (this.frame) { this.frame.play.value = 'Play'; } }; /** * Set a callback function which will be triggered when the value of the * slider bar has changed. */ Slider.prototype.setOnChangeCallback = function(callback) { this.onChangeCallback = callback; }; /** * Set the interval for playing the list * @param {Number} interval The interval in milliseconds */ Slider.prototype.setPlayInterval = function(interval) { this.playInterval = interval; }; /** * Retrieve the current play interval * @return {Number} interval The interval in milliseconds */ Slider.prototype.getPlayInterval = function(interval) { return this.playInterval; }; /** * Set looping on or off * @pararm {boolean} doLoop If true, the slider will jump to the start when * the end is passed, and will jump to the end * when the start is passed. */ Slider.prototype.setPlayLoop = function(doLoop) { this.playLoop = doLoop; }; /** * Execute the onchange callback function */ Slider.prototype.onChange = function() { if (this.onChangeCallback !== undefined) { this.onChangeCallback(); } }; /** * redraw the slider on the correct place */ Slider.prototype.redraw = function() { if (this.frame) { // resize the bar this.frame.bar.style.top = (this.frame.clientHeight/2 - this.frame.bar.offsetHeight/2) + 'px'; this.frame.bar.style.width = (this.frame.clientWidth - this.frame.prev.clientWidth - this.frame.play.clientWidth - this.frame.next.clientWidth - 30) + 'px'; // position the slider button var left = this.indexToLeft(this.index); this.frame.slide.style.left = (left) + 'px'; } }; /** * Set the list with values for the slider * @param {Array} values A javascript array with values (any type) */ Slider.prototype.setValues = function(values) { this.values = values; if (this.values.length > 0) this.setIndex(0); else this.index = undefined; }; /** * Select a value by its index * @param {Number} index */ Slider.prototype.setIndex = function(index) { if (index < this.values.length) { this.index = index; this.redraw(); this.onChange(); } else { throw 'Error: index out of range'; } }; /** * retrieve the index of the currently selected vaue * @return {Number} index */ Slider.prototype.getIndex = function() { return this.index; }; /** * retrieve the currently selected value * @return {*} value */ Slider.prototype.get = function() { return this.values[this.index]; }; Slider.prototype._onMouseDown = function(event) { // only react on left mouse button down var leftButtonDown = event.which ? (event.which === 1) : (event.button === 1); if (!leftButtonDown) return; this.startClientX = event.clientX; this.startSlideX = parseFloat(this.frame.slide.style.left); this.frame.style.cursor = 'move'; // add event listeners to handle moving the contents // we store the function onmousemove and onmouseup in the graph, so we can // remove the eventlisteners lateron in the function mouseUp() var me = this; this.onmousemove = function (event) {me._onMouseMove(event);}; this.onmouseup = function (event) {me._onMouseUp(event);}; util.addEventListener(document, 'mousemove', this.onmousemove); util.addEventListener(document, 'mouseup', this.onmouseup); util.preventDefault(event); }; Slider.prototype.leftToIndex = function (left) { var width = parseFloat(this.frame.bar.style.width) - this.frame.slide.clientWidth - 10; var x = left - 3; var index = Math.round(x / width * (this.values.length-1)); if (index < 0) index = 0; if (index > this.values.length-1) index = this.values.length-1; return index; }; Slider.prototype.indexToLeft = function (index) { var width = parseFloat(this.frame.bar.style.width) - this.frame.slide.clientWidth - 10; var x = index / (this.values.length-1) * width; var left = x + 3; return left; }; Slider.prototype._onMouseMove = function (event) { var diff = event.clientX - this.startClientX; var x = this.startSlideX + diff; var index = this.leftToIndex(x); this.setIndex(index); util.preventDefault(); }; Slider.prototype._onMouseUp = function (event) { this.frame.style.cursor = 'auto'; // remove event listeners util.removeEventListener(document, 'mousemove', this.onmousemove); util.removeEventListener(document, 'mouseup', this.onmouseup); util.preventDefault(); }; module.exports = Slider; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { /** * @prototype StepNumber * The class StepNumber is an iterator for Numbers. You provide a start and end * value, and a best step size. StepNumber itself rounds to fixed values and * a finds the step that best fits the provided step. * * If prettyStep is true, the step size is chosen as close as possible to the * provided step, but being a round value like 1, 2, 5, 10, 20, 50, .... * * Example usage: * var step = new StepNumber(0, 10, 2.5, true); * step.start(); * while (!step.end()) { * alert(step.getCurrent()); * step.next(); * } * * Version: 1.0 * * @param {Number} start The start value * @param {Number} end The end value * @param {Number} step Optional. Step size. Must be a positive value. * @param {boolean} prettyStep Optional. If true, the step size is rounded * To a pretty step size (like 1, 2, 5, 10, 20, 50, ...) */ function StepNumber(start, end, step, prettyStep) { // set default values this._start = 0; this._end = 0; this._step = 1; this.prettyStep = true; this.precision = 5; this._current = 0; this.setRange(start, end, step, prettyStep); }; /** * Set a new range: start, end and step. * * @param {Number} start The start value * @param {Number} end The end value * @param {Number} step Optional. Step size. Must be a positive value. * @param {boolean} prettyStep Optional. If true, the step size is rounded * To a pretty step size (like 1, 2, 5, 10, 20, 50, ...) */ StepNumber.prototype.setRange = function(start, end, step, prettyStep) { this._start = start ? start : 0; this._end = end ? end : 0; this.setStep(step, prettyStep); }; /** * Set a new step size * @param {Number} step New step size. Must be a positive value * @param {boolean} prettyStep Optional. If true, the provided step is rounded * to a pretty step size (like 1, 2, 5, 10, 20, 50, ...) */ StepNumber.prototype.setStep = function(step, prettyStep) { if (step === undefined || step <= 0) return; if (prettyStep !== undefined) this.prettyStep = prettyStep; if (this.prettyStep === true) this._step = StepNumber.calculatePrettyStep(step); else this._step = step; }; /** * Calculate a nice step size, closest to the desired step size. * Returns a value in one of the ranges 1*10^n, 2*10^n, or 5*10^n, where n is an * integer Number. For example 1, 2, 5, 10, 20, 50, etc... * @param {Number} step Desired step size * @return {Number} Nice step size */ StepNumber.calculatePrettyStep = function (step) { var log10 = function (x) {return Math.log(x) / Math.LN10;}; // try three steps (multiple of 1, 2, or 5 var step1 = Math.pow(10, Math.round(log10(step))), step2 = 2 * Math.pow(10, Math.round(log10(step / 2))), step5 = 5 * Math.pow(10, Math.round(log10(step / 5))); // choose the best step (closest to minimum step) var prettyStep = step1; if (Math.abs(step2 - step) <= Math.abs(prettyStep - step)) prettyStep = step2; if (Math.abs(step5 - step) <= Math.abs(prettyStep - step)) prettyStep = step5; // for safety if (prettyStep <= 0) { prettyStep = 1; } return prettyStep; }; /** * returns the current value of the step * @return {Number} current value */ StepNumber.prototype.getCurrent = function () { return parseFloat(this._current.toPrecision(this.precision)); }; /** * returns the current step size * @return {Number} current step size */ StepNumber.prototype.getStep = function () { return this._step; }; /** * Set the current value to the largest value smaller than start, which * is a multiple of the step size */ StepNumber.prototype.start = function() { this._current = this._start - this._start % this._step; }; /** * Do a step, add the step size to the current value */ StepNumber.prototype.next = function () { this._current += this._step; }; /** * Returns true whether the end is reached * @return {boolean} True if the current value has passed the end value. */ StepNumber.prototype.end = function () { return (this._current > this._end); }; module.exports = StepNumber; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { var Emitter = __webpack_require__(46); var Hammer = __webpack_require__(41); var util = __webpack_require__(1); var DataSet = __webpack_require__(3); var DataView = __webpack_require__(4); var Range = __webpack_require__(15); var Core = __webpack_require__(42); var TimeAxis = __webpack_require__(27); var CurrentTime = __webpack_require__(19); var CustomTime = __webpack_require__(20); var ItemSet = __webpack_require__(24); /** * Create a timeline visualization * @param {HTMLElement} container * @param {vis.DataSet | Array | google.visualization.DataTable} [items] * @param {Object} [options] See Timeline.setOptions for the available options. * @constructor */ function Timeline (container, items, options) { // mix the core properties in here for (var coreProp in Core.prototype) { if (Core.prototype.hasOwnProperty(coreProp) && !Timeline.prototype.hasOwnProperty(coreProp)) { Timeline.prototype[coreProp] = Core.prototype[coreProp]; } } if (!(this instanceof Timeline)) { throw new SyntaxError('Constructor must be called with the new operator'); } var me = this; this.defaultOptions = { start: null, end: null, autoResize: true, orientation: 'bottom', width: null, height: null, maxHeight: null, minHeight: null }; this.options = util.deepExtend({}, this.defaultOptions); // Create the DOM, props, and emitter this._create(container); // all components listed here will be repainted automatically this.components = []; this.body = { dom: this.dom, domProps: this.props, emitter: { on: this.on.bind(this), off: this.off.bind(this), emit: this.emit.bind(this) }, util: { snap: null, // will be specified after TimeAxis is created toScreen: me._toScreen.bind(me), toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width toTime: me._toTime.bind(me), toGlobalTime : me._toGlobalTime.bind(me) } }; // range this.range = new Range(this.body); this.components.push(this.range); this.body.range = this.range; // time axis this.timeAxis = new TimeAxis(this.body); this.components.push(this.timeAxis); this.body.util.snap = this.timeAxis.snap.bind(this.timeAxis); // current time bar this.currentTime = new CurrentTime(this.body); this.components.push(this.currentTime); // custom time bar // Note: time bar will be attached in this.setOptions when selected this.customTime = new CustomTime(this.body); this.components.push(this.customTime); // item set this.itemSet = new ItemSet(this.body); this.components.push(this.itemSet); this.itemsData = null; // DataSet this.groupsData = null; // DataSet // apply options if (options) { this.setOptions(options); } // create itemset if (items) { this.setItems(items); } else { this.redraw(); } } /** * Set options. Options will be passed to all components loaded in the Timeline. * @param {Object} [options] * {String} orientation * Vertical orientation for the Timeline, * can be 'bottom' (default) or 'top'. * {String | Number} width * Width for the timeline, a number in pixels or * a css string like '1000px' or '75%'. '100%' by default. * {String | Number} height * Fixed height for the Timeline, a number in pixels or * a css string like '400px' or '75%'. If undefined, * The Timeline will automatically size such that * its contents fit. * {String | Number} minHeight * Minimum height for the Timeline, a number in pixels or * a css string like '400px' or '75%'. * {String | Number} maxHeight * Maximum height for the Timeline, a number in pixels or * a css string like '400px' or '75%'. * {Number | Date | String} start * Start date for the visible window * {Number | Date | String} end * End date for the visible window */ Timeline.prototype.setOptions = function (options) { if (options) { // copy the known options var fields = ['width', 'height', 'minHeight', 'maxHeight', 'autoResize', 'start', 'end', 'orientation']; util.selectiveExtend(fields, this.options, options); // enable/disable autoResize this._initAutoResize(); } // propagate options to all components this.components.forEach(function (component) { component.setOptions(options); }); // TODO: remove deprecation error one day (deprecated since version 0.8.0) if (options && options.order) { throw new Error('Option order is deprecated. There is no replacement for this feature.'); } // redraw everything this.redraw(); }; /** * Set items * @param {vis.DataSet | Array | google.visualization.DataTable | null} items */ Timeline.prototype.setItems = function(items) { var initialLoad = (this.itemsData == null); // convert to type DataSet when needed var newDataSet; if (!items) { newDataSet = null; } else if (items instanceof DataSet || items instanceof DataView) { newDataSet = items; } else { // turn an array into a dataset newDataSet = new DataSet(items, { type: { start: 'Date', end: 'Date' } }); } // set items this.itemsData = newDataSet; this.itemSet && this.itemSet.setItems(newDataSet); if (initialLoad && ('start' in this.options || 'end' in this.options)) { this.fit(); var start = ('start' in this.options) ? util.convert(this.options.start, 'Date') : null; var end = ('end' in this.options) ? util.convert(this.options.end, 'Date') : null; this.setWindow(start, end); } }; /** * Set groups * @param {vis.DataSet | Array | google.visualization.DataTable} groups */ Timeline.prototype.setGroups = function(groups) { // convert to type DataSet when needed var newDataSet; if (!groups) { newDataSet = null; } else if (groups instanceof DataSet || groups instanceof DataView) { newDataSet = groups; } else { // turn an array into a dataset newDataSet = new DataSet(groups); } this.groupsData = newDataSet; this.itemSet.setGroups(newDataSet); }; /** * Set selected items by their id. Replaces the current selection * Unknown id's are silently ignored. * @param {Array} [ids] An array with zero or more id's of the items to be * selected. If ids is an empty array, all items will be * unselected. */ Timeline.prototype.setSelection = function(ids) { this.itemSet && this.itemSet.setSelection(ids); }; /** * Get the selected items by their id * @return {Array} ids The ids of the selected items */ Timeline.prototype.getSelection = function() { return this.itemSet && this.itemSet.getSelection() || []; }; /** * Get the data range of the item set. * @returns {{min: Date, max: Date}} range A range with a start and end Date. * When no minimum is found, min==null * When no maximum is found, max==null */ Timeline.prototype.getItemRange = function() { // calculate min from start filed var dataset = this.itemsData.getDataSet(), min = null, max = null; if (dataset) { // calculate the minimum value of the field 'start' var minItem = dataset.min('start'); min = minItem ? util.convert(minItem.start, 'Date').valueOf() : null; // Note: we convert first to Date and then to number because else // a conversion from ISODate to Number will fail // calculate maximum value of fields 'start' and 'end' var maxStartItem = dataset.max('start'); if (maxStartItem) { max = util.convert(maxStartItem.start, 'Date').valueOf(); } var maxEndItem = dataset.max('end'); if (maxEndItem) { if (max == null) { max = util.convert(maxEndItem.end, 'Date').valueOf(); } else { max = Math.max(max, util.convert(maxEndItem.end, 'Date').valueOf()); } } } return { min: (min != null) ? new Date(min) : null, max: (max != null) ? new Date(max) : null }; }; module.exports = Timeline; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { var Emitter = __webpack_require__(46); var Hammer = __webpack_require__(41); var util = __webpack_require__(1); var DataSet = __webpack_require__(3); var DataView = __webpack_require__(4); var Range = __webpack_require__(15); var Core = __webpack_require__(42); var TimeAxis = __webpack_require__(27); var CurrentTime = __webpack_require__(19); var CustomTime = __webpack_require__(20); var LineGraph = __webpack_require__(26); /** * Create a timeline visualization * @param {HTMLElement} container * @param {vis.DataSet | Array | google.visualization.DataTable} [items] * @param {Object} [options] See Graph2d.setOptions for the available options. * @constructor */ function Graph2d (container, items, options, groups) { for (var coreProp in Core.prototype) { if (Core.prototype.hasOwnProperty(coreProp) && !Graph2d.prototype.hasOwnProperty(coreProp)) { Graph2d.prototype[coreProp] = Core.prototype[coreProp]; } } var me = this; this.defaultOptions = { start: null, end: null, autoResize: true, orientation: 'bottom', width: null, height: null, maxHeight: null, minHeight: null }; this.options = util.deepExtend({}, this.defaultOptions); // Create the DOM, props, and emitter this._create(container); // all components listed here will be repainted automatically this.components = []; this.body = { dom: this.dom, domProps: this.props, emitter: { on: this.on.bind(this), off: this.off.bind(this), emit: this.emit.bind(this) }, util: { snap: null, // will be specified after TimeAxis is created toScreen: me._toScreen.bind(me), toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width toTime: me._toTime.bind(me), toGlobalTime : me._toGlobalTime.bind(me) } }; // range this.range = new Range(this.body); this.components.push(this.range); this.body.range = this.range; // time axis this.timeAxis = new TimeAxis(this.body); this.components.push(this.timeAxis); this.body.util.snap = this.timeAxis.snap.bind(this.timeAxis); // current time bar this.currentTime = new CurrentTime(this.body); this.components.push(this.currentTime); // custom time bar // Note: time bar will be attached in this.setOptions when selected this.customTime = new CustomTime(this.body); this.components.push(this.customTime); // item set this.linegraph = new LineGraph(this.body); this.components.push(this.linegraph); this.itemsData = null; // DataSet this.groupsData = null; // DataSet // apply options if (options) { this.setOptions(options); } // IMPORTANT: THIS HAPPENS BEFORE SET ITEMS! if (groups) { this.setGroups(groups); } // create itemset if (items) { this.setItems(items); } else { this.redraw(); } } /** * Set options. Options will be passed to all components loaded in the Graph2d. * @param {Object} [options] * {String} orientation * Vertical orientation for the Graph2d, * can be 'bottom' (default) or 'top'. * {String | Number} width * Width for the timeline, a number in pixels or * a css string like '1000px' or '75%'. '100%' by default. * {String | Number} height * Fixed height for the Graph2d, a number in pixels or * a css string like '400px' or '75%'. If undefined, * The Graph2d will automatically size such that * its contents fit. * {String | Number} minHeight * Minimum height for the Graph2d, a number in pixels or * a css string like '400px' or '75%'. * {String | Number} maxHeight * Maximum height for the Graph2d, a number in pixels or * a css string like '400px' or '75%'. * {Number | Date | String} start * Start date for the visible window * {Number | Date | String} end * End date for the visible window */ Graph2d.prototype.setOptions = function (options) { if (options) { // copy the known options var fields = ['width', 'height', 'minHeight', 'maxHeight', 'autoResize', 'start', 'end', 'orientation']; util.selectiveExtend(fields, this.options, options); // enable/disable autoResize this._initAutoResize(); } // propagate options to all components this.components.forEach(function (component) { component.setOptions(options); }); // TODO: remove deprecation error one day (deprecated since version 0.8.0) if (options && options.order) { throw new Error('Option order is deprecated. There is no replacement for this feature.'); } // redraw everything this.redraw(); }; /** * Set items * @param {vis.DataSet | Array | google.visualization.DataTable | null} items */ Graph2d.prototype.setItems = function(items) { var initialLoad = (this.itemsData == null); // convert to type DataSet when needed var newDataSet; if (!items) { newDataSet = null; } else if (items instanceof DataSet || items instanceof DataView) { newDataSet = items; } else { // turn an array into a dataset newDataSet = new DataSet(items, { type: { start: 'Date', end: 'Date' } }); } // set items this.itemsData = newDataSet; this.linegraph && this.linegraph.setItems(newDataSet); if (initialLoad && ('start' in this.options || 'end' in this.options)) { this.fit(); var start = ('start' in this.options) ? util.convert(this.options.start, 'Date') : null; var end = ('end' in this.options) ? util.convert(this.options.end, 'Date') : null; this.setWindow(start, end); } }; /** * Set groups * @param {vis.DataSet | Array | google.visualization.DataTable} groups */ Graph2d.prototype.setGroups = function(groups) { // convert to type DataSet when needed var newDataSet; if (!groups) { newDataSet = null; } else if (groups instanceof DataSet || groups instanceof DataView) { newDataSet = groups; } else { // turn an array into a dataset newDataSet = new DataSet(groups); } this.groupsData = newDataSet; this.linegraph.setGroups(newDataSet); }; /** * Returns an object containing an SVG element with the icon of the group (size determined by iconWidth and iconHeight), the label of the group (content) and the yAxisOrientation of the group (left or right). * @param groupId * @param width * @param height */ Graph2d.prototype.getLegend = function(groupId, width, height) { if (width === undefined) {width = 15;} if (height === undefined) {height = 15;} if (this.linegraph.groups[groupId] !== undefined) { return this.linegraph.groups[groupId].getLegend(width,height); } else { return "cannot find group:" + groupId; } } /** * This checks if the visible option of the supplied group (by ID) is true or false. * @param groupId * @returns {*} */ Graph2d.prototype.isGroupVisible = function(groupId) { if (this.linegraph.groups[groupId] !== undefined) { return this.linegraph.groups[groupId].visible; } else { return false; } } /** * Get the data range of the item set. * @returns {{min: Date, max: Date}} range A range with a start and end Date. * When no minimum is found, min==null * When no maximum is found, max==null */ Graph2d.prototype.getItemRange = function() { var min = null; var max = null; // calculate min from start filed for (var groupId in this.linegraph.groups) { if (this.linegraph.groups.hasOwnProperty(groupId)) { if (this.linegraph.groups[groupId].visible == true) { for (var i = 0; i < this.linegraph.groups[groupId].itemsData.length; i++) { var item = this.linegraph.groups[groupId].itemsData[i]; var value = util.convert(item.x, 'Date').valueOf(); min = min == null ? value : min > value ? value : min; max = max == null ? value : max < value ? value : max; } } } } return { min: (min != null) ? new Date(min) : null, max: (max != null) ? new Date(max) : null }; }; module.exports = Graph2d; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { /** * @constructor DataStep * The class DataStep is an iterator for data for the lineGraph. You provide a start data point and an * end data point. The class itself determines the best scale (step size) based on the * provided start Date, end Date, and minimumStep. * * If minimumStep is provided, the step size is chosen as close as possible * to the minimumStep but larger than minimumStep. If minimumStep is not * provided, the scale is set to 1 DAY. * The minimumStep should correspond with the onscreen size of about 6 characters * * Alternatively, you can set a scale by hand. * After creation, you can initialize the class by executing first(). Then you * can iterate from the start date to the end date via next(). You can check if * the end date is reached with the function hasNext(). After each step, you can * retrieve the current date via getCurrent(). * The DataStep has scales ranging from milliseconds, seconds, minutes, hours, * days, to years. * * Version: 1.2 * * @param {Date} [start] The start date, for example new Date(2010, 9, 21) * or new Date(2010, 9, 21, 23, 45, 00) * @param {Date} [end] The end date * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds */ function DataStep(start, end, minimumStep, containerHeight, forcedStepSize) { // variables this.current = 0; this.autoScale = true; this.stepIndex = 0; this.step = 1; this.scale = 1; this.marginStart; this.marginEnd; this.majorSteps = [1, 2, 5, 10]; this.minorSteps = [0.25, 0.5, 1, 2]; this.setRange(start, end, minimumStep, containerHeight, forcedStepSize); } /** * Set a new range * If minimumStep is provided, the step size is chosen as close as possible * to the minimumStep but larger than minimumStep. If minimumStep is not * provided, the scale is set to 1 DAY. * The minimumStep should correspond with the onscreen size of about 6 characters * @param {Number} [start] The start date and time. * @param {Number} [end] The end date and time. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds */ DataStep.prototype.setRange = function(start, end, minimumStep, containerHeight, forcedStepSize) { this._start = start; this._end = end; if (start == end) { this._start = start - 0.75; this._end = end + 1; } if (this.autoScale) { this.setMinimumStep(minimumStep, containerHeight, forcedStepSize); } this.setFirst(); }; /** * Automatically determine the scale that bests fits the provided minimum step * @param {Number} [minimumStep] The minimum step size in milliseconds */ DataStep.prototype.setMinimumStep = function(minimumStep, containerHeight) { // round to floor var size = this._end - this._start; var safeSize = size * 1.1; var minimumStepValue = minimumStep * (safeSize / containerHeight); var orderOfMagnitude = Math.round(Math.log(safeSize)/Math.LN10); var minorStepIdx = -1; var magnitudefactor = Math.pow(10,orderOfMagnitude); var start = 0; if (orderOfMagnitude < 0) { start = orderOfMagnitude; } var solutionFound = false; for (var i = start; Math.abs(i) <= Math.abs(orderOfMagnitude); i++) { magnitudefactor = Math.pow(10,i); for (var j = 0; j < this.minorSteps.length; j++) { var stepSize = magnitudefactor * this.minorSteps[j]; if (stepSize >= minimumStepValue) { solutionFound = true; minorStepIdx = j; break; } } if (solutionFound == true) { break; } } this.stepIndex = minorStepIdx; this.scale = magnitudefactor; this.step = magnitudefactor * this.minorSteps[minorStepIdx]; }; /** * Set the range iterator to the start date. */ DataStep.prototype.first = function() { this.setFirst(); }; /** * Round the current date to the first minor date value * This must be executed once when the current date is set to start Date */ DataStep.prototype.setFirst = function() { var niceStart = this._start - (this.scale * this.minorSteps[this.stepIndex]); var niceEnd = this._end + (this.scale * this.minorSteps[this.stepIndex]); this.marginEnd = this.roundToMinor(niceEnd); this.marginStart = this.roundToMinor(niceStart); this.marginRange = this.marginEnd - this.marginStart; this.current = this.marginEnd; }; DataStep.prototype.roundToMinor = function(value) { var rounded = value - (value % (this.scale * this.minorSteps[this.stepIndex])); if (value % (this.scale * this.minorSteps[this.stepIndex]) > 0.5 * (this.scale * this.minorSteps[this.stepIndex])) { return rounded + (this.scale * this.minorSteps[this.stepIndex]); } else { return rounded; } } /** * Check if the there is a next step * @return {boolean} true if the current date has not passed the end date */ DataStep.prototype.hasNext = function () { return (this.current >= this.marginStart); }; /** * Do the next step */ DataStep.prototype.next = function() { var prev = this.current; this.current -= this.step; // safety mechanism: if current time is still unchanged, move to the end if (this.current == prev) { this.current = this._end; } }; /** * Do the next step */ DataStep.prototype.previous = function() { this.current += this.step; this.marginEnd += this.step; this.marginRange = this.marginEnd - this.marginStart; }; /** * Get the current datetime * @return {String} current The current date */ DataStep.prototype.getCurrent = function() { var toPrecision = '' + Number(this.current).toPrecision(5); for (var i = toPrecision.length-1; i > 0; i--) { if (toPrecision[i] == "0") { toPrecision = toPrecision.slice(0,i); } else if (toPrecision[i] == "." || toPrecision[i] == ",") { toPrecision = toPrecision.slice(0,i); break; } else{ break; } } return toPrecision; }; /** * Snap a date to a rounded value. * The snap intervals are dependent on the current scale and step. * @param {Date} date the date to be snapped. * @return {Date} snappedDate */ DataStep.prototype.snap = function(date) { }; /** * Check if the current value is a major value (for example when the step * is DAY, a major value is each first day of the MONTH) * @return {boolean} true if current date is major, else false. */ DataStep.prototype.isMajor = function() { return (this.current % (this.scale * this.majorSteps[this.stepIndex]) == 0); }; module.exports = DataStep; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var hammerUtil = __webpack_require__(43); var moment = __webpack_require__(40); var Component = __webpack_require__(18); /** * @constructor Range * A Range controls a numeric range with a start and end value. * The Range adjusts the range based on mouse events or programmatic changes, * and triggers events when the range is changing or has been changed. * @param {{dom: Object, domProps: Object, emitter: Emitter}} body * @param {Object} [options] See description at Range.setOptions */ function Range(body, options) { var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0); this.start = now.clone().add('days', -3).valueOf(); // Number this.end = now.clone().add('days', 4).valueOf(); // Number this.body = body; // default options this.defaultOptions = { start: null, end: null, direction: 'horizontal', // 'horizontal' or 'vertical' moveable: true, zoomable: true, min: null, max: null, zoomMin: 10, // milliseconds zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000 // milliseconds }; this.options = util.extend({}, this.defaultOptions); this.props = { touch: {} }; // drag listeners for dragging this.body.emitter.on('dragstart', this._onDragStart.bind(this)); this.body.emitter.on('drag', this._onDrag.bind(this)); this.body.emitter.on('dragend', this._onDragEnd.bind(this)); // ignore dragging when holding this.body.emitter.on('hold', this._onHold.bind(this)); // mouse wheel for zooming this.body.emitter.on('mousewheel', this._onMouseWheel.bind(this)); this.body.emitter.on('DOMMouseScroll', this._onMouseWheel.bind(this)); // For FF // pinch to zoom this.body.emitter.on('touch', this._onTouch.bind(this)); this.body.emitter.on('pinch', this._onPinch.bind(this)); this.setOptions(options); } Range.prototype = new Component(); /** * Set options for the range controller * @param {Object} options Available options: * {Number | Date | String} start Start date for the range * {Number | Date | String} end End date for the range * {Number} min Minimum value for start * {Number} max Maximum value for end * {Number} zoomMin Set a minimum value for * (end - start). * {Number} zoomMax Set a maximum value for * (end - start). * {Boolean} moveable Enable moving of the range * by dragging. True by default * {Boolean} zoomable Enable zooming of the range * by pinching/scrolling. True by default */ Range.prototype.setOptions = function (options) { if (options) { // copy the options that we know var fields = ['direction', 'min', 'max', 'zoomMin', 'zoomMax', 'moveable', 'zoomable']; util.selectiveExtend(fields, this.options, options); if ('start' in options || 'end' in options) { // apply a new range. both start and end are optional this.setRange(options.start, options.end); } } }; /** * Test whether direction has a valid value * @param {String} direction 'horizontal' or 'vertical' */ function validateDirection (direction) { if (direction != 'horizontal' && direction != 'vertical') { throw new TypeError('Unknown direction "' + direction + '". ' + 'Choose "horizontal" or "vertical".'); } } /** * Set a new start and end range * @param {Number} [start] * @param {Number} [end] */ Range.prototype.setRange = function(start, end) { var changed = this._applyRange(start, end); if (changed) { var params = { start: new Date(this.start), end: new Date(this.end) }; this.body.emitter.emit('rangechange', params); this.body.emitter.emit('rangechanged', params); } }; /** * Set a new start and end range. This method is the same as setRange, but * does not trigger a range change and range changed event, and it returns * true when the range is changed * @param {Number} [start] * @param {Number} [end] * @return {Boolean} changed * @private */ Range.prototype._applyRange = function(start, end) { var newStart = (start != null) ? util.convert(start, 'Date').valueOf() : this.start, newEnd = (end != null) ? util.convert(end, 'Date').valueOf() : this.end, max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null, min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null, diff; // check for valid number if (isNaN(newStart) || newStart === null) { throw new Error('Invalid start "' + start + '"'); } if (isNaN(newEnd) || newEnd === null) { throw new Error('Invalid end "' + end + '"'); } // prevent start < end if (newEnd < newStart) { newEnd = newStart; } // prevent start < min if (min !== null) { if (newStart < min) { diff = (min - newStart); newStart += diff; newEnd += diff; // prevent end > max if (max != null) { if (newEnd > max) { newEnd = max; } } } } // prevent end > max if (max !== null) { if (newEnd > max) { diff = (newEnd - max); newStart -= diff; newEnd -= diff; // prevent start < min if (min != null) { if (newStart < min) { newStart = min; } } } } // prevent (end-start) < zoomMin if (this.options.zoomMin !== null) { var zoomMin = parseFloat(this.options.zoomMin); if (zoomMin < 0) { zoomMin = 0; } if ((newEnd - newStart) < zoomMin) { if ((this.end - this.start) === zoomMin) { // ignore this action, we are already zoomed to the minimum newStart = this.start; newEnd = this.end; } else { // zoom to the minimum diff = (zoomMin - (newEnd - newStart)); newStart -= diff / 2; newEnd += diff / 2; } } } // prevent (end-start) > zoomMax if (this.options.zoomMax !== null) { var zoomMax = parseFloat(this.options.zoomMax); if (zoomMax < 0) { zoomMax = 0; } if ((newEnd - newStart) > zoomMax) { if ((this.end - this.start) === zoomMax) { // ignore this action, we are already zoomed to the maximum newStart = this.start; newEnd = this.end; } else { // zoom to the maximum diff = ((newEnd - newStart) - zoomMax); newStart += diff / 2; newEnd -= diff / 2; } } } var changed = (this.start != newStart || this.end != newEnd); this.start = newStart; this.end = newEnd; return changed; }; /** * Retrieve the current range. * @return {Object} An object with start and end properties */ Range.prototype.getRange = function() { return { start: this.start, end: this.end }; }; /** * Calculate the conversion offset and scale for current range, based on * the provided width * @param {Number} width * @returns {{offset: number, scale: number}} conversion */ Range.prototype.conversion = function (width) { return Range.conversion(this.start, this.end, width); }; /** * Static method to calculate the conversion offset and scale for a range, * based on the provided start, end, and width * @param {Number} start * @param {Number} end * @param {Number} width * @returns {{offset: number, scale: number}} conversion */ Range.conversion = function (start, end, width) { if (width != 0 && (end - start != 0)) { return { offset: start, scale: width / (end - start) } } else { return { offset: 0, scale: 1 }; } }; /** * Start dragging horizontally or vertically * @param {Event} event * @private */ Range.prototype._onDragStart = function(event) { // only allow dragging when configured as movable if (!this.options.moveable) return; // refuse to drag when we where pinching to prevent the timeline make a jump // when releasing the fingers in opposite order from the touch screen if (!this.props.touch.allowDragging) return; this.props.touch.start = this.start; this.props.touch.end = this.end; if (this.body.dom.root) { this.body.dom.root.style.cursor = 'move'; } }; /** * Perform dragging operation * @param {Event} event * @private */ Range.prototype._onDrag = function (event) { // only allow dragging when configured as movable if (!this.options.moveable) return; var direction = this.options.direction; validateDirection(direction); // refuse to drag when we where pinching to prevent the timeline make a jump // when releasing the fingers in opposite order from the touch screen if (!this.props.touch.allowDragging) return; var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY, interval = (this.props.touch.end - this.props.touch.start), width = (direction == 'horizontal') ? this.body.domProps.center.width : this.body.domProps.center.height, diffRange = -delta / width * interval; this._applyRange(this.props.touch.start + diffRange, this.props.touch.end + diffRange); this.body.emitter.emit('rangechange', { start: new Date(this.start), end: new Date(this.end) }); }; /** * Stop dragging operation * @param {event} event * @private */ Range.prototype._onDragEnd = function (event) { // only allow dragging when configured as movable if (!this.options.moveable) return; // refuse to drag when we where pinching to prevent the timeline make a jump // when releasing the fingers in opposite order from the touch screen if (!this.props.touch.allowDragging) return; if (this.body.dom.root) { this.body.dom.root.style.cursor = 'auto'; } // fire a rangechanged event this.body.emitter.emit('rangechanged', { start: new Date(this.start), end: new Date(this.end) }); }; /** * Event handler for mouse wheel event, used to zoom * Code from http://adomas.org/javascript-mouse-wheel/ * @param {Event} event * @private */ Range.prototype._onMouseWheel = function(event) { // only allow zooming when configured as zoomable and moveable if (!(this.options.zoomable && this.options.moveable)) return; // retrieve delta var delta = 0; if (event.wheelDelta) { /* IE/Opera. */ delta = event.wheelDelta / 120; } else if (event.detail) { /* Mozilla case. */ // In Mozilla, sign of delta is different than in IE. // Also, delta is multiple of 3. delta = -event.detail / 3; } // If delta is nonzero, handle it. // Basically, delta is now positive if wheel was scrolled up, // and negative, if wheel was scrolled down. if (delta) { // perform the zoom action. Delta is normally 1 or -1 // adjust a negative delta such that zooming in with delta 0.1 // equals zooming out with a delta -0.1 var scale; if (delta < 0) { scale = 1 - (delta / 5); } else { scale = 1 / (1 + (delta / 5)) ; } // calculate center, the date to zoom around var gesture = hammerUtil.fakeGesture(this, event), pointer = getPointer(gesture.center, this.body.dom.center), pointerDate = this._pointerToDate(pointer); this.zoom(scale, pointerDate); } // Prevent default actions caused by mouse wheel // (else the page and timeline both zoom and scroll) event.preventDefault(); }; /** * Start of a touch gesture * @private */ Range.prototype._onTouch = function (event) { this.props.touch.start = this.start; this.props.touch.end = this.end; this.props.touch.allowDragging = true; this.props.touch.center = null; }; /** * On start of a hold gesture * @private */ Range.prototype._onHold = function () { this.props.touch.allowDragging = false; }; /** * Handle pinch event * @param {Event} event * @private */ Range.prototype._onPinch = function (event) { // only allow zooming when configured as zoomable and moveable if (!(this.options.zoomable && this.options.moveable)) return; this.props.touch.allowDragging = false; if (event.gesture.touches.length > 1) { if (!this.props.touch.center) { this.props.touch.center = getPointer(event.gesture.center, this.body.dom.center); } var scale = 1 / event.gesture.scale, initDate = this._pointerToDate(this.props.touch.center); // calculate new start and end var newStart = parseInt(initDate + (this.props.touch.start - initDate) * scale); var newEnd = parseInt(initDate + (this.props.touch.end - initDate) * scale); // apply new range this.setRange(newStart, newEnd); } }; /** * Helper function to calculate the center date for zooming * @param {{x: Number, y: Number}} pointer * @return {number} date * @private */ Range.prototype._pointerToDate = function (pointer) { var conversion; var direction = this.options.direction; validateDirection(direction); if (direction == 'horizontal') { var width = this.body.domProps.center.width; conversion = this.conversion(width); return pointer.x / conversion.scale + conversion.offset; } else { var height = this.body.domProps.center.height; conversion = this.conversion(height); return pointer.y / conversion.scale + conversion.offset; } }; /** * Get the pointer location relative to the location of the dom element * @param {{pageX: Number, pageY: Number}} touch * @param {Element} element HTML DOM element * @return {{x: Number, y: Number}} pointer * @private */ function getPointer (touch, element) { return { x: touch.pageX - util.getAbsoluteLeft(element), y: touch.pageY - util.getAbsoluteTop(element) }; } /** * Zoom the range the given scale in or out. Start and end date will * be adjusted, and the timeline will be redrawn. You can optionally give a * date around which to zoom. * For example, try scale = 0.9 or 1.1 * @param {Number} scale Scaling factor. Values above 1 will zoom out, * values below 1 will zoom in. * @param {Number} [center] Value representing a date around which will * be zoomed. */ Range.prototype.zoom = function(scale, center) { // if centerDate is not provided, take it half between start Date and end Date if (center == null) { center = (this.start + this.end) / 2; } // calculate new start and end var newStart = center + (this.start - center) * scale; var newEnd = center + (this.end - center) * scale; this.setRange(newStart, newEnd); }; /** * Move the range with a given delta to the left or right. Start and end * value will be adjusted. For example, try delta = 0.1 or -0.1 * @param {Number} delta Moving amount. Positive value will move right, * negative value will move left */ Range.prototype.move = function(delta) { // zoom start Date and end Date relative to the centerDate var diff = (this.end - this.start); // apply new values var newStart = this.start + diff * delta; var newEnd = this.end + diff * delta; // TODO: reckon with min and max range this.start = newStart; this.end = newEnd; }; /** * Move the range to a new center point * @param {Number} moveTo New center point of the range */ Range.prototype.moveTo = function(moveTo) { var center = (this.start + this.end) / 2; var diff = center - moveTo; // calculate new start and end var newStart = this.start - diff; var newEnd = this.end - diff; this.setRange(newStart, newEnd); }; module.exports = Range; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { // Utility functions for ordering and stacking of items var EPSILON = 0.001; // used when checking collisions, to prevent round-off errors /** * Order items by their start data * @param {Item[]} items */ exports.orderByStart = function(items) { items.sort(function (a, b) { return a.data.start - b.data.start; }); }; /** * Order items by their end date. If they have no end date, their start date * is used. * @param {Item[]} items */ exports.orderByEnd = function(items) { items.sort(function (a, b) { var aTime = ('end' in a.data) ? a.data.end : a.data.start, bTime = ('end' in b.data) ? b.data.end : b.data.start; return aTime - bTime; }); }; /** * Adjust vertical positions of the items such that they don't overlap each * other. * @param {Item[]} items * All visible items * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin * Margins between items and between items and the axis. * @param {boolean} [force=false] * If true, all items will be repositioned. If false (default), only * items having a top===null will be re-stacked */ exports.stack = function(items, margin, force) { var i, iMax; if (force) { // reset top position of all items for (i = 0, iMax = items.length; i < iMax; i++) { items[i].top = null; } } // calculate new, non-overlapping positions for (i = 0, iMax = items.length; i < iMax; i++) { var item = items[i]; if (item.top === null) { // initialize top position item.top = margin.axis; do { // TODO: optimize checking for overlap. when there is a gap without items, // you only need to check for items from the next item on, not from zero var collidingItem = null; for (var j = 0, jj = items.length; j < jj; j++) { var other = items[j]; if (other.top !== null && other !== item && exports.collision(item, other, margin.item)) { collidingItem = other; break; } } if (collidingItem != null) { // There is a collision. Reposition the items above the colliding element item.top = collidingItem.top + collidingItem.height + margin.item.vertical; } } while (collidingItem); } } }; /** * Adjust vertical positions of the items without stacking them * @param {Item[]} items * All visible items * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin * Margins between items and between items and the axis. */ exports.nostack = function(items, margin) { var i, iMax; // reset top position of all items for (i = 0, iMax = items.length; i < iMax; i++) { items[i].top = margin.axis; } }; /** * Test if the two provided items collide * The items must have parameters left, width, top, and height. * @param {Item} a The first item * @param {Item} b The second item * @param {{horizontal: number, vertical: number}} margin * An object containing a horizontal and vertical * minimum required margin. * @return {boolean} true if a and b collide, else false */ exports.collision = function(a, b, margin) { return ((a.left - margin.horizontal + EPSILON) < (b.left + b.width) && (a.left + a.width + margin.horizontal - EPSILON) > b.left && (a.top - margin.vertical + EPSILON) < (b.top + b.height) && (a.top + a.height + margin.vertical - EPSILON) > b.top); }; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { var moment = __webpack_require__(40); /** * @constructor TimeStep * The class TimeStep is an iterator for dates. You provide a start date and an * end date. The class itself determines the best scale (step size) based on the * provided start Date, end Date, and minimumStep. * * If minimumStep is provided, the step size is chosen as close as possible * to the minimumStep but larger than minimumStep. If minimumStep is not * provided, the scale is set to 1 DAY. * The minimumStep should correspond with the onscreen size of about 6 characters * * Alternatively, you can set a scale by hand. * After creation, you can initialize the class by executing first(). Then you * can iterate from the start date to the end date via next(). You can check if * the end date is reached with the function hasNext(). After each step, you can * retrieve the current date via getCurrent(). * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours, * days, to years. * * Version: 1.2 * * @param {Date} [start] The start date, for example new Date(2010, 9, 21) * or new Date(2010, 9, 21, 23, 45, 00) * @param {Date} [end] The end date * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds */ function TimeStep(start, end, minimumStep) { // variables this.current = new Date(); this._start = new Date(); this._end = new Date(); this.autoScale = true; this.scale = TimeStep.SCALE.DAY; this.step = 1; // initialize the range this.setRange(start, end, minimumStep); } /// enum scale TimeStep.SCALE = { MILLISECOND: 1, SECOND: 2, MINUTE: 3, HOUR: 4, DAY: 5, WEEKDAY: 6, MONTH: 7, YEAR: 8 }; /** * Set a new range * If minimumStep is provided, the step size is chosen as close as possible * to the minimumStep but larger than minimumStep. If minimumStep is not * provided, the scale is set to 1 DAY. * The minimumStep should correspond with the onscreen size of about 6 characters * @param {Date} [start] The start date and time. * @param {Date} [end] The end date and time. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds */ TimeStep.prototype.setRange = function(start, end, minimumStep) { if (!(start instanceof Date) || !(end instanceof Date)) { throw "No legal start or end date in method setRange"; } this._start = (start != undefined) ? new Date(start.valueOf()) : new Date(); this._end = (end != undefined) ? new Date(end.valueOf()) : new Date(); if (this.autoScale) { this.setMinimumStep(minimumStep); } }; /** * Set the range iterator to the start date. */ TimeStep.prototype.first = function() { this.current = new Date(this._start.valueOf()); this.roundToMinor(); }; /** * Round the current date to the first minor date value * This must be executed once when the current date is set to start Date */ TimeStep.prototype.roundToMinor = function() { // round to floor // IMPORTANT: we have no breaks in this switch! (this is no bug) //noinspection FallthroughInSwitchStatementJS switch (this.scale) { case TimeStep.SCALE.YEAR: this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step)); this.current.setMonth(0); case TimeStep.SCALE.MONTH: this.current.setDate(1); case TimeStep.SCALE.DAY: // intentional fall through case TimeStep.SCALE.WEEKDAY: this.current.setHours(0); case TimeStep.SCALE.HOUR: this.current.setMinutes(0); case TimeStep.SCALE.MINUTE: this.current.setSeconds(0); case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0); //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds } if (this.step != 1) { // round down to the first minor value that is a multiple of the current step size switch (this.scale) { case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break; case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break; case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break; case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break; case TimeStep.SCALE.WEEKDAY: // intentional fall through case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break; case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break; case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break; default: break; } } }; /** * Check if the there is a next step * @return {boolean} true if the current date has not passed the end date */ TimeStep.prototype.hasNext = function () { return (this.current.valueOf() <= this._end.valueOf()); }; /** * Do the next step */ TimeStep.prototype.next = function() { var prev = this.current.valueOf(); // Two cases, needed to prevent issues with switching daylight savings // (end of March and end of October) if (this.current.getMonth() < 6) { switch (this.scale) { case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break; case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break; case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break; case TimeStep.SCALE.HOUR: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60); // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...) var h = this.current.getHours(); this.current.setHours(h - (h % this.step)); break; case TimeStep.SCALE.WEEKDAY: // intentional fall through case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break; case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break; case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break; default: break; } } else { switch (this.scale) { case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break; case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break; case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break; case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break; case TimeStep.SCALE.WEEKDAY: // intentional fall through case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break; case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break; case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break; default: break; } } if (this.step != 1) { // round down to the correct major value switch (this.scale) { case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break; case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break; case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break; case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break; case TimeStep.SCALE.WEEKDAY: // intentional fall through case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break; case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break; case TimeStep.SCALE.YEAR: break; // nothing to do for year default: break; } } // safety mechanism: if current time is still unchanged, move to the end if (this.current.valueOf() == prev) { this.current = new Date(this._end.valueOf()); } }; /** * Get the current datetime * @return {Date} current The current date */ TimeStep.prototype.getCurrent = function() { return this.current; }; /** * Set a custom scale. Autoscaling will be disabled. * For example setScale(SCALE.MINUTES, 5) will result * in minor steps of 5 minutes, and major steps of an hour. * * @param {TimeStep.SCALE} newScale * A scale. Choose from SCALE.MILLISECOND, * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR, * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH, * SCALE.YEAR. * @param {Number} newStep A step size, by default 1. Choose for * example 1, 2, 5, or 10. */ TimeStep.prototype.setScale = function(newScale, newStep) { this.scale = newScale; if (newStep > 0) { this.step = newStep; } this.autoScale = false; }; /** * Enable or disable autoscaling * @param {boolean} enable If true, autoascaling is set true */ TimeStep.prototype.setAutoScale = function (enable) { this.autoScale = enable; }; /** * Automatically determine the scale that bests fits the provided minimum step * @param {Number} [minimumStep] The minimum step size in milliseconds */ TimeStep.prototype.setMinimumStep = function(minimumStep) { if (minimumStep == undefined) { return; } var stepYear = (1000 * 60 * 60 * 24 * 30 * 12); var stepMonth = (1000 * 60 * 60 * 24 * 30); var stepDay = (1000 * 60 * 60 * 24); var stepHour = (1000 * 60 * 60); var stepMinute = (1000 * 60); var stepSecond = (1000); var stepMillisecond= (1); // find the smallest step that is larger than the provided minimumStep if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;} if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;} if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;} if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;} if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;} if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;} if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;} if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;} if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;} if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;} if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;} if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;} if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;} if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;} if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;} if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;} if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;} if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;} if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;} if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;} if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;} if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;} if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;} if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;} if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;} if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;} if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;} if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;} if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;} }; /** * Snap a date to a rounded value. * The snap intervals are dependent on the current scale and step. * @param {Date} date the date to be snapped. * @return {Date} snappedDate */ TimeStep.prototype.snap = function(date) { var clone = new Date(date.valueOf()); if (this.scale == TimeStep.SCALE.YEAR) { var year = clone.getFullYear() + Math.round(clone.getMonth() / 12); clone.setFullYear(Math.round(year / this.step) * this.step); clone.setMonth(0); clone.setDate(0); clone.setHours(0); clone.setMinutes(0); clone.setSeconds(0); clone.setMilliseconds(0); } else if (this.scale == TimeStep.SCALE.MONTH) { if (clone.getDate() > 15) { clone.setDate(1); clone.setMonth(clone.getMonth() + 1); // important: first set Date to 1, after that change the month. } else { clone.setDate(1); } clone.setHours(0); clone.setMinutes(0); clone.setSeconds(0); clone.setMilliseconds(0); } else if (this.scale == TimeStep.SCALE.DAY) { //noinspection FallthroughInSwitchStatementJS switch (this.step) { case 5: case 2: clone.setHours(Math.round(clone.getHours() / 24) * 24); break; default: clone.setHours(Math.round(clone.getHours() / 12) * 12); break; } clone.setMinutes(0); clone.setSeconds(0); clone.setMilliseconds(0); } else if (this.scale == TimeStep.SCALE.WEEKDAY) { //noinspection FallthroughInSwitchStatementJS switch (this.step) { case 5: case 2: clone.setHours(Math.round(clone.getHours() / 12) * 12); break; default: clone.setHours(Math.round(clone.getHours() / 6) * 6); break; } clone.setMinutes(0); clone.setSeconds(0); clone.setMilliseconds(0); } else if (this.scale == TimeStep.SCALE.HOUR) { switch (this.step) { case 4: clone.setMinutes(Math.round(clone.getMinutes() / 60) * 60); break; default: clone.setMinutes(Math.round(clone.getMinutes() / 30) * 30); break; } clone.setSeconds(0); clone.setMilliseconds(0); } else if (this.scale == TimeStep.SCALE.MINUTE) { //noinspection FallthroughInSwitchStatementJS switch (this.step) { case 15: case 10: clone.setMinutes(Math.round(clone.getMinutes() / 5) * 5); clone.setSeconds(0); break; case 5: clone.setSeconds(Math.round(clone.getSeconds() / 60) * 60); break; default: clone.setSeconds(Math.round(clone.getSeconds() / 30) * 30); break; } clone.setMilliseconds(0); } else if (this.scale == TimeStep.SCALE.SECOND) { //noinspection FallthroughInSwitchStatementJS switch (this.step) { case 15: case 10: clone.setSeconds(Math.round(clone.getSeconds() / 5) * 5); clone.setMilliseconds(0); break; case 5: clone.setMilliseconds(Math.round(clone.getMilliseconds() / 1000) * 1000); break; default: clone.setMilliseconds(Math.round(clone.getMilliseconds() / 500) * 500); break; } } else if (this.scale == TimeStep.SCALE.MILLISECOND) { var step = this.step > 5 ? this.step / 2 : 1; clone.setMilliseconds(Math.round(clone.getMilliseconds() / step) * step); } return clone; }; /** * Check if the current value is a major value (for example when the step * is DAY, a major value is each first day of the MONTH) * @return {boolean} true if current date is major, else false. */ TimeStep.prototype.isMajor = function() { switch (this.scale) { case TimeStep.SCALE.MILLISECOND: return (this.current.getMilliseconds() == 0); case TimeStep.SCALE.SECOND: return (this.current.getSeconds() == 0); case TimeStep.SCALE.MINUTE: return (this.current.getHours() == 0) && (this.current.getMinutes() == 0); // Note: this is no bug. Major label is equal for both minute and hour scale case TimeStep.SCALE.HOUR: return (this.current.getHours() == 0); case TimeStep.SCALE.WEEKDAY: // intentional fall through case TimeStep.SCALE.DAY: return (this.current.getDate() == 1); case TimeStep.SCALE.MONTH: return (this.current.getMonth() == 0); case TimeStep.SCALE.YEAR: return false; default: return false; } }; /** * Returns formatted text for the minor axislabel, depending on the current * date and the scale. For example when scale is MINUTE, the current time is * formatted as "hh:mm". * @param {Date} [date] custom date. if not provided, current date is taken */ TimeStep.prototype.getLabelMinor = function(date) { if (date == undefined) { date = this.current; } switch (this.scale) { case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS'); case TimeStep.SCALE.SECOND: return moment(date).format('s'); case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm'); case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm'); case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D'); case TimeStep.SCALE.DAY: return moment(date).format('D'); case TimeStep.SCALE.MONTH: return moment(date).format('MMM'); case TimeStep.SCALE.YEAR: return moment(date).format('YYYY'); default: return ''; } }; /** * Returns formatted text for the major axis label, depending on the current * date and the scale. For example when scale is MINUTE, the major scale is * hours, and the hour will be formatted as "hh". * @param {Date} [date] custom date. if not provided, current date is taken */ TimeStep.prototype.getLabelMajor = function(date) { if (date == undefined) { date = this.current; } //noinspection FallthroughInSwitchStatementJS switch (this.scale) { case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss'); case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm'); case TimeStep.SCALE.MINUTE: case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM'); case TimeStep.SCALE.WEEKDAY: case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY'); case TimeStep.SCALE.MONTH: return moment(date).format('YYYY'); case TimeStep.SCALE.YEAR: return ''; default: return ''; } }; module.exports = TimeStep; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { /** * Prototype for visual components * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} [body] * @param {Object} [options] */ function Component (body, options) { this.options = null; this.props = null; } /** * Set options for the component. The new options will be merged into the * current options. * @param {Object} options */ Component.prototype.setOptions = function(options) { if (options) { util.extend(this.options, options); } }; /** * Repaint the component * @return {boolean} Returns true if the component is resized */ Component.prototype.redraw = function() { // should be implemented by the component return false; }; /** * Destroy the component. Cleanup DOM and event listeners */ Component.prototype.destroy = function() { // should be implemented by the component }; /** * Test whether the component is resized since the last time _isResized() was * called. * @return {Boolean} Returns true if the component is resized * @protected */ Component.prototype._isResized = function() { var resized = (this.props._previousWidth !== this.props.width || this.props._previousHeight !== this.props.height); this.props._previousWidth = this.props.width; this.props._previousHeight = this.props.height; return resized; }; module.exports = Component; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var Component = __webpack_require__(18); /** * A current time bar * @param {{range: Range, dom: Object, domProps: Object}} body * @param {Object} [options] Available parameters: * {Boolean} [showCurrentTime] * @constructor CurrentTime * @extends Component */ function CurrentTime (body, options) { this.body = body; // default options this.defaultOptions = { showCurrentTime: true }; this.options = util.extend({}, this.defaultOptions); this._create(); this.setOptions(options); } CurrentTime.prototype = new Component(); /** * Create the HTML DOM for the current time bar * @private */ CurrentTime.prototype._create = function() { var bar = document.createElement('div'); bar.className = 'currenttime'; bar.style.position = 'absolute'; bar.style.top = '0px'; bar.style.height = '100%'; this.bar = bar; }; /** * Destroy the CurrentTime bar */ CurrentTime.prototype.destroy = function () { this.options.showCurrentTime = false; this.redraw(); // will remove the bar from the DOM and stop refreshing this.body = null; }; /** * Set options for the component. Options will be merged in current options. * @param {Object} options Available parameters: * {boolean} [showCurrentTime] */ CurrentTime.prototype.setOptions = function(options) { if (options) { // copy all options that we know util.selectiveExtend(['showCurrentTime'], this.options, options); } }; /** * Repaint the component * @return {boolean} Returns true if the component is resized */ CurrentTime.prototype.redraw = function() { if (this.options.showCurrentTime) { var parent = this.body.dom.backgroundVertical; if (this.bar.parentNode != parent) { // attach to the dom if (this.bar.parentNode) { this.bar.parentNode.removeChild(this.bar); } parent.appendChild(this.bar); this.start(); } var now = new Date(); var x = this.body.util.toScreen(now); this.bar.style.left = x + 'px'; this.bar.title = 'Current time: ' + now; } else { // remove the line from the DOM if (this.bar.parentNode) { this.bar.parentNode.removeChild(this.bar); } this.stop(); } return false; }; /** * Start auto refreshing the current time bar */ CurrentTime.prototype.start = function() { var me = this; function update () { me.stop(); // determine interval to refresh var scale = me.body.range.conversion(me.body.domProps.center.width).scale; var interval = 1 / scale / 10; if (interval < 30) interval = 30; if (interval > 1000) interval = 1000; me.redraw(); // start a timer to adjust for the new time me.currentTimeTimer = setTimeout(update, interval); } update(); }; /** * Stop auto refreshing the current time bar */ CurrentTime.prototype.stop = function() { if (this.currentTimeTimer !== undefined) { clearTimeout(this.currentTimeTimer); delete this.currentTimeTimer; } }; module.exports = CurrentTime; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { var Hammer = __webpack_require__(41); var util = __webpack_require__(1); var Component = __webpack_require__(18); /** * A custom time bar * @param {{range: Range, dom: Object}} body * @param {Object} [options] Available parameters: * {Boolean} [showCustomTime] * @constructor CustomTime * @extends Component */ function CustomTime (body, options) { this.body = body; // default options this.defaultOptions = { showCustomTime: false }; this.options = util.extend({}, this.defaultOptions); this.customTime = new Date(); this.eventParams = {}; // stores state parameters while dragging the bar // create the DOM this._create(); this.setOptions(options); } CustomTime.prototype = new Component(); /** * Set options for the component. Options will be merged in current options. * @param {Object} options Available parameters: * {boolean} [showCustomTime] */ CustomTime.prototype.setOptions = function(options) { if (options) { // copy all options that we know util.selectiveExtend(['showCustomTime'], this.options, options); } }; /** * Create the DOM for the custom time * @private */ CustomTime.prototype._create = function() { var bar = document.createElement('div'); bar.className = 'customtime'; bar.style.position = 'absolute'; bar.style.top = '0px'; bar.style.height = '100%'; this.bar = bar; var drag = document.createElement('div'); drag.style.position = 'relative'; drag.style.top = '0px'; drag.style.left = '-10px'; drag.style.height = '100%'; drag.style.width = '20px'; bar.appendChild(drag); // attach event listeners this.hammer = Hammer(bar, { prevent_default: true }); this.hammer.on('dragstart', this._onDragStart.bind(this)); this.hammer.on('drag', this._onDrag.bind(this)); this.hammer.on('dragend', this._onDragEnd.bind(this)); }; /** * Destroy the CustomTime bar */ CustomTime.prototype.destroy = function () { this.options.showCustomTime = false; this.redraw(); // will remove the bar from the DOM this.hammer.enable(false); this.hammer = null; this.body = null; }; /** * Repaint the component * @return {boolean} Returns true if the component is resized */ CustomTime.prototype.redraw = function () { if (this.options.showCustomTime) { var parent = this.body.dom.backgroundVertical; if (this.bar.parentNode != parent) { // attach to the dom if (this.bar.parentNode) { this.bar.parentNode.removeChild(this.bar); } parent.appendChild(this.bar); } var x = this.body.util.toScreen(this.customTime); this.bar.style.left = x + 'px'; this.bar.title = 'Time: ' + this.customTime; } else { // remove the line from the DOM if (this.bar.parentNode) { this.bar.parentNode.removeChild(this.bar); } } return false; }; /** * Set custom time. * @param {Date} time */ CustomTime.prototype.setCustomTime = function(time) { this.customTime = new Date(time.valueOf()); this.redraw(); }; /** * Retrieve the current custom time. * @return {Date} customTime */ CustomTime.prototype.getCustomTime = function() { return new Date(this.customTime.valueOf()); }; /** * Start moving horizontally * @param {Event} event * @private */ CustomTime.prototype._onDragStart = function(event) { this.eventParams.dragging = true; this.eventParams.customTime = this.customTime; event.stopPropagation(); event.preventDefault(); }; /** * Perform moving operating. * @param {Event} event * @private */ CustomTime.prototype._onDrag = function (event) { if (!this.eventParams.dragging) return; var deltaX = event.gesture.deltaX, x = this.body.util.toScreen(this.eventParams.customTime) + deltaX, time = this.body.util.toTime(x); this.setCustomTime(time); // fire a timechange event this.body.emitter.emit('timechange', { time: new Date(this.customTime.valueOf()) }); event.stopPropagation(); event.preventDefault(); }; /** * Stop moving operating. * @param {event} event * @private */ CustomTime.prototype._onDragEnd = function (event) { if (!this.eventParams.dragging) return; // fire a timechanged event this.body.emitter.emit('timechanged', { time: new Date(this.customTime.valueOf()) }); event.stopPropagation(); event.preventDefault(); }; module.exports = CustomTime; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var DOMutil = __webpack_require__(2); var Component = __webpack_require__(18); var DataStep = __webpack_require__(14); /** * A horizontal time axis * @param {Object} [options] See DataAxis.setOptions for the available * options. * @constructor DataAxis * @extends Component * @param body */ function DataAxis (body, options, svg) { this.id = util.randomUUID(); this.body = body; this.defaultOptions = { orientation: 'left', // supported: 'left', 'right' showMinorLabels: true, showMajorLabels: true, icons: true, majorLinesOffset: 7, minorLinesOffset: 4, labelOffsetX: 10, labelOffsetY: 2, iconWidth: 20, width: '40px', visible: true }; this.linegraphSVG = svg; this.props = {}; this.DOMelements = { // dynamic elements lines: {}, labels: {} }; this.dom = {}; this.range = {start:0, end:0}; this.options = util.extend({}, this.defaultOptions); this.conversionFactor = 1; this.setOptions(options); this.width = Number(('' + this.options.width).replace("px","")); this.minWidth = this.width; this.height = this.linegraphSVG.offsetHeight; this.stepPixels = 25; this.stepPixelsForced = 25; this.lineOffset = 0; this.master = true; this.svgElements = {}; this.groups = {}; this.amountOfGroups = 0; // create the HTML DOM this._create(); } DataAxis.prototype = new Component(); DataAxis.prototype.addGroup = function(label, graphOptions) { if (!this.groups.hasOwnProperty(label)) { this.groups[label] = graphOptions; } this.amountOfGroups += 1; }; DataAxis.prototype.updateGroup = function(label, graphOptions) { this.groups[label] = graphOptions; }; DataAxis.prototype.removeGroup = function(label) { if (this.groups.hasOwnProperty(label)) { delete this.groups[label]; this.amountOfGroups -= 1; } }; DataAxis.prototype.setOptions = function (options) { if (options) { var redraw = false; if (this.options.orientation != options.orientation && options.orientation !== undefined) { redraw = true; } var fields = [ 'orientation', 'showMinorLabels', 'showMajorLabels', 'icons', 'majorLinesOffset', 'minorLinesOffset', 'labelOffsetX', 'labelOffsetY', 'iconWidth', 'width', 'visible']; util.selectiveExtend(fields, this.options, options); this.minWidth = Number(('' + this.options.width).replace("px","")); if (redraw == true && this.dom.frame) { this.hide(); this.show(); } } }; /** * Create the HTML DOM for the DataAxis */ DataAxis.prototype._create = function() { this.dom.frame = document.createElement('div'); this.dom.frame.style.width = this.options.width; this.dom.frame.style.height = this.height; this.dom.lineContainer = document.createElement('div'); this.dom.lineContainer.style.width = '100%'; this.dom.lineContainer.style.height = this.height; // create svg element for graph drawing. this.svg = document.createElementNS('http://www.w3.org/2000/svg',"svg"); this.svg.style.position = "absolute"; this.svg.style.top = '0px'; this.svg.style.height = '100%'; this.svg.style.width = '100%'; this.svg.style.display = "block"; this.dom.frame.appendChild(this.svg); }; DataAxis.prototype._redrawGroupIcons = function () { DOMutil.prepareElements(this.svgElements); var x; var iconWidth = this.options.iconWidth; var iconHeight = 15; var iconOffset = 4; var y = iconOffset + 0.5 * iconHeight; if (this.options.orientation == 'left') { x = iconOffset; } else { x = this.width - iconWidth - iconOffset; } for (var groupId in this.groups) { if (this.groups.hasOwnProperty(groupId)) { if (this.groups[groupId].visible == true) { this.groups[groupId].drawIcon(x, y, this.svgElements, this.svg, iconWidth, iconHeight); y += iconHeight + iconOffset; } } } DOMutil.cleanupElements(this.svgElements); }; /** * Create the HTML DOM for the DataAxis */ DataAxis.prototype.show = function() { if (!this.dom.frame.parentNode) { if (this.options.orientation == 'left') { this.body.dom.left.appendChild(this.dom.frame); } else { this.body.dom.right.appendChild(this.dom.frame); } } if (!this.dom.lineContainer.parentNode) { this.body.dom.backgroundHorizontal.appendChild(this.dom.lineContainer); } }; /** * Create the HTML DOM for the DataAxis */ DataAxis.prototype.hide = function() { if (this.dom.frame.parentNode) { this.dom.frame.parentNode.removeChild(this.dom.frame); } if (this.dom.lineContainer.parentNode) { this.dom.lineContainer.parentNode.removeChild(this.dom.lineContainer); } }; /** * Set a range (start and end) * @param end * @param start * @param end */ DataAxis.prototype.setRange = function (start, end) { this.range.start = start; this.range.end = end; }; /** * Repaint the component * @return {boolean} Returns true if the component is resized */ DataAxis.prototype.redraw = function () { var changeCalled = false; var activeGroups = 0; for (var groupId in this.groups) { if (this.groups.hasOwnProperty(groupId)) { if (this.groups[groupId].visible == true) { activeGroups++; } } } if (this.amountOfGroups == 0 || activeGroups == 0) { this.hide(); } else { this.show(); this.height = Number(this.linegraphSVG.style.height.replace("px","")); // svg offsetheight did not work in firefox and explorer... this.dom.lineContainer.style.height = this.height + 'px'; this.width = this.options.visible == true ? Number(('' + this.options.width).replace("px","")) : 0; var props = this.props; var frame = this.dom.frame; // update classname frame.className = 'dataaxis'; // calculate character width and height this._calculateCharSize(); var orientation = this.options.orientation; var showMinorLabels = this.options.showMinorLabels; var showMajorLabels = this.options.showMajorLabels; // determine the width and height of the elemens for the axis props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0; props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0; props.minorLineWidth = this.body.dom.backgroundHorizontal.offsetWidth - this.lineOffset - this.width + 2 * this.options.minorLinesOffset; props.minorLineHeight = 1; props.majorLineWidth = this.body.dom.backgroundHorizontal.offsetWidth - this.lineOffset - this.width + 2 * this.options.majorLinesOffset; props.majorLineHeight = 1; // take frame offline while updating (is almost twice as fast) if (orientation == 'left') { frame.style.top = '0'; frame.style.left = '0'; frame.style.bottom = ''; frame.style.width = this.width + 'px'; frame.style.height = this.height + "px"; } else { // right frame.style.top = ''; frame.style.bottom = '0'; frame.style.left = '0'; frame.style.width = this.width + 'px'; frame.style.height = this.height + "px"; } changeCalled = this._redrawLabels(); if (this.options.icons == true) { this._redrawGroupIcons(); } } return changeCalled; }; /** * Repaint major and minor text labels and vertical grid lines * @private */ DataAxis.prototype._redrawLabels = function () { DOMutil.prepareElements(this.DOMelements.lines); DOMutil.prepareElements(this.DOMelements.labels); var orientation = this.options['orientation']; // calculate range and step (step such that we have space for 7 characters per label) var minimumStep = this.master ? this.props.majorCharHeight || 10 : this.stepPixelsForced; var step = new DataStep(this.range.start, this.range.end, minimumStep, this.dom.frame.offsetHeight); this.step = step; step.first(); // get the distance in pixels for a step var stepPixels = this.dom.frame.offsetHeight / ((step.marginRange / step.step) + 1); this.stepPixels = stepPixels; var amountOfSteps = this.height / stepPixels; var stepDifference = 0; if (this.master == false) { stepPixels = this.stepPixelsForced; stepDifference = Math.round((this.height / stepPixels) - amountOfSteps); for (var i = 0; i < 0.5 * stepDifference; i++) { step.previous(); } amountOfSteps = this.height / stepPixels; } this.valueAtZero = step.marginEnd; var marginStartPos = 0; // do not draw the first label var max = 1; step.next(); this.maxLabelSize = 0; var y = 0; while (max < Math.round(amountOfSteps)) { y = Math.round(max * stepPixels); marginStartPos = max * stepPixels; var isMajor = step.isMajor(); if (this.options['showMinorLabels'] && isMajor == false || this.master == false && this.options['showMinorLabels'] == true) { this._redrawLabel(y - 2, step.getCurrent(), orientation, 'yAxis minor', this.props.minorCharHeight); } if (isMajor && this.options['showMajorLabels'] && this.master == true || this.options['showMinorLabels'] == false && this.master == false && isMajor == true) { if (y >= 0) { this._redrawLabel(y - 2, step.getCurrent(), orientation, 'yAxis major', this.props.majorCharHeight); } this._redrawLine(y, orientation, 'grid horizontal major', this.options.majorLinesOffset, this.props.majorLineWidth); } else { this._redrawLine(y, orientation, 'grid horizontal minor', this.options.minorLinesOffset, this.props.minorLineWidth); } step.next(); max++; } this.conversionFactor = marginStartPos/((amountOfSteps-1) * step.step); var offset = this.options.icons == true ? this.options.iconWidth + this.options.labelOffsetX + 15 : this.options.labelOffsetX + 15; // this will resize the yAxis to accomodate the labels. if (this.maxLabelSize > (this.width - offset) && this.options.visible == true) { this.width = this.maxLabelSize + offset; this.options.width = this.width + "px"; DOMutil.cleanupElements(this.DOMelements.lines); DOMutil.cleanupElements(this.DOMelements.labels); this.redraw(); return true; } // this will resize the yAxis if it is too big for the labels. else if (this.maxLabelSize < (this.width - offset) && this.options.visible == true && this.width > this.minWidth) { this.width = Math.max(this.minWidth,this.maxLabelSize + offset); this.options.width = this.width + "px"; DOMutil.cleanupElements(this.DOMelements.lines); DOMutil.cleanupElements(this.DOMelements.labels); this.redraw(); return true; } else { DOMutil.cleanupElements(this.DOMelements.lines); DOMutil.cleanupElements(this.DOMelements.labels); return false; } }; /** * Create a label for the axis at position x * @private * @param y * @param text * @param orientation * @param className * @param characterHeight */ DataAxis.prototype._redrawLabel = function (y, text, orientation, className, characterHeight) { // reuse redundant label var label = DOMutil.getDOMElement('div',this.DOMelements.labels, this.dom.frame); //this.dom.redundant.labels.shift(); label.className = className; label.innerHTML = text; if (orientation == 'left') { label.style.left = '-' + this.options.labelOffsetX + 'px'; label.style.textAlign = "right"; } else { label.style.right = '-' + this.options.labelOffsetX + 'px'; label.style.textAlign = "left"; } label.style.top = y - 0.5 * characterHeight + this.options.labelOffsetY + 'px'; text += ''; var largestWidth = Math.max(this.props.majorCharWidth,this.props.minorCharWidth); if (this.maxLabelSize < text.length * largestWidth) { this.maxLabelSize = text.length * largestWidth; } }; /** * Create a minor line for the axis at position y * @param y * @param orientation * @param className * @param offset * @param width */ DataAxis.prototype._redrawLine = function (y, orientation, className, offset, width) { if (this.master == true) { var line = DOMutil.getDOMElement('div',this.DOMelements.lines, this.dom.lineContainer);//this.dom.redundant.lines.shift(); line.className = className; line.innerHTML = ''; if (orientation == 'left') { line.style.left = (this.width - offset) + 'px'; } else { line.style.right = (this.width - offset) + 'px'; } line.style.width = width + 'px'; line.style.top = y + 'px'; } }; DataAxis.prototype.convertValue = function (value) { var invertedValue = this.valueAtZero - value; var convertedValue = invertedValue * this.conversionFactor; return convertedValue; // the -2 is to compensate for the borders }; /** * Determine the size of text on the axis (both major and minor axis). * The size is calculated only once and then cached in this.props. * @private */ DataAxis.prototype._calculateCharSize = function () { // determine the char width and height on the minor axis if (!('minorCharHeight' in this.props)) { var textMinor = document.createTextNode('0'); var measureCharMinor = document.createElement('DIV'); measureCharMinor.className = 'yAxis minor measure'; measureCharMinor.appendChild(textMinor); this.dom.frame.appendChild(measureCharMinor); this.props.minorCharHeight = measureCharMinor.clientHeight; this.props.minorCharWidth = measureCharMinor.clientWidth; this.dom.frame.removeChild(measureCharMinor); } if (!('majorCharHeight' in this.props)) { var textMajor = document.createTextNode('0'); var measureCharMajor = document.createElement('DIV'); measureCharMajor.className = 'yAxis major measure'; measureCharMajor.appendChild(textMajor); this.dom.frame.appendChild(measureCharMajor); this.props.majorCharHeight = measureCharMajor.clientHeight; this.props.majorCharWidth = measureCharMajor.clientWidth; this.dom.frame.removeChild(measureCharMajor); } }; /** * Snap a date to a rounded value. * The snap intervals are dependent on the current scale and step. * @param {Date} date the date to be snapped. * @return {Date} snappedDate */ DataAxis.prototype.snap = function(date) { return this.step.snap(date); }; module.exports = DataAxis; /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var DOMutil = __webpack_require__(2); /** * @constructor Group * @param {Number | String} groupId * @param {Object} data * @param {ItemSet} itemSet */ function GraphGroup (group, groupId, options, groupsUsingDefaultStyles) { this.id = groupId; var fields = ['sampling','style','sort','yAxisOrientation','barChart','drawPoints','shaded','catmullRom'] this.options = util.selectiveBridgeObject(fields,options); this.usingDefaultStyle = group.className === undefined; this.groupsUsingDefaultStyles = groupsUsingDefaultStyles; this.zeroPosition = 0; this.update(group); if (this.usingDefaultStyle == true) { this.groupsUsingDefaultStyles[0] += 1; } this.itemsData = []; this.visible = group.visible === undefined ? true : group.visible; } GraphGroup.prototype.setItems = function(items) { if (items != null) { this.itemsData = items; if (this.options.sort == true) { this.itemsData.sort(function (a,b) {return a.x - b.x;}) } } else { this.itemsData = []; } }; GraphGroup.prototype.setZeroPosition = function(pos) { this.zeroPosition = pos; }; GraphGroup.prototype.setOptions = function(options) { if (options !== undefined) { var fields = ['sampling','style','sort','yAxisOrientation','barChart']; util.selectiveDeepExtend(fields, this.options, options); util.mergeOptions(this.options, options,'catmullRom'); util.mergeOptions(this.options, options,'drawPoints'); util.mergeOptions(this.options, options,'shaded'); if (options.catmullRom) { if (typeof options.catmullRom == 'object') { if (options.catmullRom.parametrization) { if (options.catmullRom.parametrization == 'uniform') { this.options.catmullRom.alpha = 0; } else if (options.catmullRom.parametrization == 'chordal') { this.options.catmullRom.alpha = 1.0; } else { this.options.catmullRom.parametrization = 'centripetal'; this.options.catmullRom.alpha = 0.5; } } } } } }; GraphGroup.prototype.update = function(group) { this.group = group; this.content = group.content || 'graph'; this.className = group.className || this.className || "graphGroup" + this.groupsUsingDefaultStyles[0] % 10; this.visible = group.visible === undefined ? true : group.visible; this.setOptions(group.options); }; GraphGroup.prototype.drawIcon = function(x, y, JSONcontainer, SVGcontainer, iconWidth, iconHeight) { var fillHeight = iconHeight * 0.5; var path, fillPath; var outline = DOMutil.getSVGElement("rect", JSONcontainer, SVGcontainer); outline.setAttributeNS(null, "x", x); outline.setAttributeNS(null, "y", y - fillHeight); outline.setAttributeNS(null, "width", iconWidth); outline.setAttributeNS(null, "height", 2*fillHeight); outline.setAttributeNS(null, "class", "outline"); if (this.options.style == 'line') { path = DOMutil.getSVGElement("path", JSONcontainer, SVGcontainer); path.setAttributeNS(null, "class", this.className); path.setAttributeNS(null, "d", "M" + x + ","+y+" L" + (x + iconWidth) + ","+y+""); if (this.options.shaded.enabled == true) { fillPath = DOMutil.getSVGElement("path", JSONcontainer, SVGcontainer); if (this.options.shaded.orientation == 'top') { fillPath.setAttributeNS(null, "d", "M"+x+", " + (y - fillHeight) + "L"+x+","+y+" L"+ (x + iconWidth) + ","+y+" L"+ (x + iconWidth) + "," + (y - fillHeight)); } else { fillPath.setAttributeNS(null, "d", "M"+x+","+y+" " + "L"+x+"," + (y + fillHeight) + " " + "L"+ (x + iconWidth) + "," + (y + fillHeight) + "L"+ (x + iconWidth) + ","+y); } fillPath.setAttributeNS(null, "class", this.className + " iconFill"); } if (this.options.drawPoints.enabled == true) { DOMutil.drawPoint(x + 0.5 * iconWidth,y, this, JSONcontainer, SVGcontainer); } } else { var barWidth = Math.round(0.3 * iconWidth); var bar1Height = Math.round(0.4 * iconHeight); var bar2Height = Math.round(0.75 * iconHeight); var offset = Math.round((iconWidth - (2 * barWidth))/3); DOMutil.drawBar(x + 0.5*barWidth + offset , y + fillHeight - bar1Height - 1, barWidth, bar1Height, this.className + ' bar', JSONcontainer, SVGcontainer); DOMutil.drawBar(x + 1.5*barWidth + offset + 2, y + fillHeight - bar2Height - 1, barWidth, bar2Height, this.className + ' bar', JSONcontainer, SVGcontainer); } }; /** * * @param iconWidth * @param iconHeight * @returns {{icon: HTMLElement, label: (group.content|*|string), orientation: (.options.yAxisOrientation|*)}} */ GraphGroup.prototype.getLegend = function(iconWidth, iconHeight) { var svg = document.createElementNS('http://www.w3.org/2000/svg',"svg"); this.drawIcon(0,0.5*iconHeight,[],svg,iconWidth,iconHeight); return {icon: svg, label: this.content, orientation:this.options.yAxisOrientation}; } module.exports = GraphGroup; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var stack = __webpack_require__(16); var ItemRange = __webpack_require__(31); /** * @constructor Group * @param {Number | String} groupId * @param {Object} data * @param {ItemSet} itemSet */ function Group (groupId, data, itemSet) { this.groupId = groupId; this.itemSet = itemSet; this.dom = {}; this.props = { label: { width: 0, height: 0 } }; this.className = null; this.items = {}; // items filtered by groupId of this group this.visibleItems = []; // items currently visible in window this.orderedItems = { // items sorted by start and by end byStart: [], byEnd: [] }; this._create(); this.setData(data); } /** * Create DOM elements for the group * @private */ Group.prototype._create = function() { var label = document.createElement('div'); label.className = 'vlabel'; this.dom.label = label; var inner = document.createElement('div'); inner.className = 'inner'; label.appendChild(inner); this.dom.inner = inner; var foreground = document.createElement('div'); foreground.className = 'group'; foreground['timeline-group'] = this; this.dom.foreground = foreground; this.dom.background = document.createElement('div'); this.dom.background.className = 'group'; this.dom.axis = document.createElement('div'); this.dom.axis.className = 'group'; // create a hidden marker to detect when the Timelines container is attached // to the DOM, or the style of a parent of the Timeline is changed from // display:none is changed to visible. this.dom.marker = document.createElement('div'); this.dom.marker.style.visibility = 'hidden'; this.dom.marker.innerHTML = '?'; this.dom.background.appendChild(this.dom.marker); }; /** * Set the group data for this group * @param {Object} data Group data, can contain properties content and className */ Group.prototype.setData = function(data) { // update contents var content = data && data.content; if (content instanceof Element) { this.dom.inner.appendChild(content); } else if (content !== undefined && content !== null) { this.dom.inner.innerHTML = content; } else { this.dom.inner.innerHTML = this.groupId || ''; // groupId can be null } // update title this.dom.label.title = data && data.title || ''; if (!this.dom.inner.firstChild) { util.addClassName(this.dom.inner, 'hidden'); } else { util.removeClassName(this.dom.inner, 'hidden'); } // update className var className = data && data.className || null; if (className != this.className) { if (this.className) { util.removeClassName(this.dom.label, className); util.removeClassName(this.dom.foreground, className); util.removeClassName(this.dom.background, className); util.removeClassName(this.dom.axis, className); } util.addClassName(this.dom.label, className); util.addClassName(this.dom.foreground, className); util.addClassName(this.dom.background, className); util.addClassName(this.dom.axis, className); } }; /** * Get the width of the group label * @return {number} width */ Group.prototype.getLabelWidth = function() { return this.props.label.width; }; /** * Repaint this group * @param {{start: number, end: number}} range * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin * @param {boolean} [restack=false] Force restacking of all items * @return {boolean} Returns true if the group is resized */ Group.prototype.redraw = function(range, margin, restack) { var resized = false; this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range); // force recalculation of the height of the items when the marker height changed // (due to the Timeline being attached to the DOM or changed from display:none to visible) var markerHeight = this.dom.marker.clientHeight; if (markerHeight != this.lastMarkerHeight) { this.lastMarkerHeight = markerHeight; util.forEach(this.items, function (item) { item.dirty = true; if (item.displayed) item.redraw(); }); restack = true; } // reposition visible items vertically if (this.itemSet.options.stack) { // TODO: ugly way to access options... stack.stack(this.visibleItems, margin, restack); } else { // no stacking stack.nostack(this.visibleItems, margin); } // recalculate the height of the group var height; var visibleItems = this.visibleItems; if (visibleItems.length) { var min = visibleItems[0].top; var max = visibleItems[0].top + visibleItems[0].height; util.forEach(visibleItems, function (item) { min = Math.min(min, item.top); max = Math.max(max, (item.top + item.height)); }); if (min > margin.axis) { // there is an empty gap between the lowest item and the axis var offset = min - margin.axis; max -= offset; util.forEach(visibleItems, function (item) { item.top -= offset; }); } height = max + margin.item.vertical / 2; } else { height = margin.axis + margin.item.vertical; } height = Math.max(height, this.props.label.height); // calculate actual size and position var foreground = this.dom.foreground; this.top = foreground.offsetTop; this.left = foreground.offsetLeft; this.width = foreground.offsetWidth; resized = util.updateProperty(this, 'height', height) || resized; // recalculate size of label resized = util.updateProperty(this.props.label, 'width', this.dom.inner.clientWidth) || resized; resized = util.updateProperty(this.props.label, 'height', this.dom.inner.clientHeight) || resized; // apply new height this.dom.background.style.height = height + 'px'; this.dom.foreground.style.height = height + 'px'; this.dom.label.style.height = height + 'px'; // update vertical position of items after they are re-stacked and the height of the group is calculated for (var i = 0, ii = this.visibleItems.length; i < ii; i++) { var item = this.visibleItems[i]; item.repositionY(); } return resized; }; /** * Show this group: attach to the DOM */ Group.prototype.show = function() { if (!this.dom.label.parentNode) { this.itemSet.dom.labelSet.appendChild(this.dom.label); } if (!this.dom.foreground.parentNode) { this.itemSet.dom.foreground.appendChild(this.dom.foreground); } if (!this.dom.background.parentNode) { this.itemSet.dom.background.appendChild(this.dom.background); } if (!this.dom.axis.parentNode) { this.itemSet.dom.axis.appendChild(this.dom.axis); } }; /** * Hide this group: remove from the DOM */ Group.prototype.hide = function() { var label = this.dom.label; if (label.parentNode) { label.parentNode.removeChild(label); } var foreground = this.dom.foreground; if (foreground.parentNode) { foreground.parentNode.removeChild(foreground); } var background = this.dom.background; if (background.parentNode) { background.parentNode.removeChild(background); } var axis = this.dom.axis; if (axis.parentNode) { axis.parentNode.removeChild(axis); } }; /** * Add an item to the group * @param {Item} item */ Group.prototype.add = function(item) { this.items[item.id] = item; item.setParent(this); if (this.visibleItems.indexOf(item) == -1) { var range = this.itemSet.body.range; // TODO: not nice accessing the range like this this._checkIfVisible(item, this.visibleItems, range); } }; /** * Remove an item from the group * @param {Item} item */ Group.prototype.remove = function(item) { delete this.items[item.id]; item.setParent(this.itemSet); // remove from visible items var index = this.visibleItems.indexOf(item); if (index != -1) this.visibleItems.splice(index, 1); // TODO: also remove from ordered items? }; /** * Remove an item from the corresponding DataSet * @param {Item} item */ Group.prototype.removeFromDataSet = function(item) { this.itemSet.removeItem(item.id); }; /** * Reorder the items */ Group.prototype.order = function() { var array = util.toArray(this.items); this.orderedItems.byStart = array; this.orderedItems.byEnd = this._constructByEndArray(array); stack.orderByStart(this.orderedItems.byStart); stack.orderByEnd(this.orderedItems.byEnd); }; /** * Create an array containing all items being a range (having an end date) * @param {Item[]} array * @returns {ItemRange[]} * @private */ Group.prototype._constructByEndArray = function(array) { var endArray = []; for (var i = 0; i < array.length; i++) { if (array[i] instanceof ItemRange) { endArray.push(array[i]); } } return endArray; }; /** * Update the visible items * @param {{byStart: Item[], byEnd: Item[]}} orderedItems All items ordered by start date and by end date * @param {Item[]} visibleItems The previously visible items. * @param {{start: number, end: number}} range Visible range * @return {Item[]} visibleItems The new visible items. * @private */ Group.prototype._updateVisibleItems = function(orderedItems, visibleItems, range) { var initialPosByStart, newVisibleItems = [], i; // first check if the items that were in view previously are still in view. // this handles the case for the ItemRange that is both before and after the current one. if (visibleItems.length > 0) { for (i = 0; i < visibleItems.length; i++) { this._checkIfVisible(visibleItems[i], newVisibleItems, range); } } // If there were no visible items previously, use binarySearch to find a visible ItemPoint or ItemRange (based on startTime) if (newVisibleItems.length == 0) { initialPosByStart = util.binarySearch(orderedItems.byStart, range, 'data','start'); } else { initialPosByStart = orderedItems.byStart.indexOf(newVisibleItems[0]); } // use visible search to find a visible ItemRange (only based on endTime) var initialPosByEnd = util.binarySearch(orderedItems.byEnd, range, 'data','end'); // if we found a initial ID to use, trace it up and down until we meet an invisible item. if (initialPosByStart != -1) { for (i = initialPosByStart; i >= 0; i--) { if (this._checkIfInvisible(orderedItems.byStart[i], newVisibleItems, range)) {break;} } for (i = initialPosByStart + 1; i < orderedItems.byStart.length; i++) { if (this._checkIfInvisible(orderedItems.byStart[i], newVisibleItems, range)) {break;} } } // if we found a initial ID to use, trace it up and down until we meet an invisible item. if (initialPosByEnd != -1) { for (i = initialPosByEnd; i >= 0; i--) { if (this._checkIfInvisible(orderedItems.byEnd[i], newVisibleItems, range)) {break;} } for (i = initialPosByEnd + 1; i < orderedItems.byEnd.length; i++) { if (this._checkIfInvisible(orderedItems.byEnd[i], newVisibleItems, range)) {break;} } } return newVisibleItems; }; /** * this function checks if an item is invisible. If it is NOT we make it visible * and add it to the global visible items. If it is, return true. * * @param {Item} item * @param {Item[]} visibleItems * @param {{start:number, end:number}} range * @returns {boolean} * @private */ Group.prototype._checkIfInvisible = function(item, visibleItems, range) { if (item.isVisible(range)) { if (!item.displayed) item.show(); item.repositionX(); if (visibleItems.indexOf(item) == -1) { visibleItems.push(item); } return false; } else { if (item.displayed) item.hide(); return true; } }; /** * this function is very similar to the _checkIfInvisible() but it does not * return booleans, hides the item if it should not be seen and always adds to * the visibleItems. * this one is for brute forcing and hiding. * * @param {Item} item * @param {Array} visibleItems * @param {{start:number, end:number}} range * @private */ Group.prototype._checkIfVisible = function(item, visibleItems, range) { if (item.isVisible(range)) { if (!item.displayed) item.show(); // reposition item horizontally item.repositionX(); visibleItems.push(item); } else { if (item.displayed) item.hide(); } }; module.exports = Group; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { var Hammer = __webpack_require__(41); var util = __webpack_require__(1); var DataSet = __webpack_require__(3); var DataView = __webpack_require__(4); var Component = __webpack_require__(18); var Group = __webpack_require__(23); var ItemBox = __webpack_require__(28); var ItemPoint = __webpack_require__(30); var ItemRange = __webpack_require__(31); var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items /** * An ItemSet holds a set of items and ranges which can be displayed in a * range. The width is determined by the parent of the ItemSet, and the height * is determined by the size of the items. * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} body * @param {Object} [options] See ItemSet.setOptions for the available options. * @constructor ItemSet * @extends Component */ function ItemSet(body, options) { this.body = body; this.defaultOptions = { type: null, // 'box', 'point', 'range' orientation: 'bottom', // 'top' or 'bottom' align: 'center', // alignment of box items stack: true, groupOrder: null, selectable: true, editable: { updateTime: false, updateGroup: false, add: false, remove: false }, onAdd: function (item, callback) { callback(item); }, onUpdate: function (item, callback) { callback(item); }, onMove: function (item, callback) { callback(item); }, onRemove: function (item, callback) { callback(item); }, margin: { item: { horizontal: 10, vertical: 10 }, axis: 20 }, padding: 5 }; // options is shared by this ItemSet and all its items this.options = util.extend({}, this.defaultOptions); // options for getting items from the DataSet with the correct type this.itemOptions = { type: {start: 'Date', end: 'Date'} }; this.conversion = { toScreen: body.util.toScreen, toTime: body.util.toTime }; this.dom = {}; this.props = {}; this.hammer = null; var me = this; this.itemsData = null; // DataSet this.groupsData = null; // DataSet // listeners for the DataSet of the items this.itemListeners = { 'add': function (event, params, senderId) { me._onAdd(params.items); }, 'update': function (event, params, senderId) { me._onUpdate(params.items); }, 'remove': function (event, params, senderId) { me._onRemove(params.items); } }; // listeners for the DataSet of the groups this.groupListeners = { 'add': function (event, params, senderId) { me._onAddGroups(params.items); }, 'update': function (event, params, senderId) { me._onUpdateGroups(params.items); }, 'remove': function (event, params, senderId) { me._onRemoveGroups(params.items); } }; this.items = {}; // object with an Item for every data item this.groups = {}; // Group object for every group this.groupIds = []; this.selection = []; // list with the ids of all selected nodes this.stackDirty = true; // if true, all items will be restacked on next redraw this.touchParams = {}; // stores properties while dragging // create the HTML DOM this._create(); this.setOptions(options); } ItemSet.prototype = new Component(); // available item types will be registered here ItemSet.types = { box: ItemBox, range: ItemRange, point: ItemPoint }; /** * Create the HTML DOM for the ItemSet */ ItemSet.prototype._create = function(){ var frame = document.createElement('div'); frame.className = 'itemset'; frame['timeline-itemset'] = this; this.dom.frame = frame; // create background panel var background = document.createElement('div'); background.className = 'background'; frame.appendChild(background); this.dom.background = background; // create foreground panel var foreground = document.createElement('div'); foreground.className = 'foreground'; frame.appendChild(foreground); this.dom.foreground = foreground; // create axis panel var axis = document.createElement('div'); axis.className = 'axis'; this.dom.axis = axis; // create labelset var labelSet = document.createElement('div'); labelSet.className = 'labelset'; this.dom.labelSet = labelSet; // create ungrouped Group this._updateUngrouped(); // attach event listeners // Note: we bind to the centerContainer for the case where the height // of the center container is larger than of the ItemSet, so we // can click in the empty area to create a new item or deselect an item. this.hammer = Hammer(this.body.dom.centerContainer, { prevent_default: true }); // drag items when selected this.hammer.on('touch', this._onTouch.bind(this)); this.hammer.on('dragstart', this._onDragStart.bind(this)); this.hammer.on('drag', this._onDrag.bind(this)); this.hammer.on('dragend', this._onDragEnd.bind(this)); // single select (or unselect) when tapping an item this.hammer.on('tap', this._onSelectItem.bind(this)); // multi select when holding mouse/touch, or on ctrl+click this.hammer.on('hold', this._onMultiSelectItem.bind(this)); // add item on doubletap this.hammer.on('doubletap', this._onAddItem.bind(this)); // attach to the DOM this.show(); }; /** * Set options for the ItemSet. Existing options will be extended/overwritten. * @param {Object} [options] The following options are available: * {String} type * Default type for the items. Choose from 'box' * (default), 'point', or 'range'. The default * Style can be overwritten by individual items. * {String} align * Alignment for the items, only applicable for * ItemBox. Choose 'center' (default), 'left', or * 'right'. * {String} orientation * Orientation of the item set. Choose 'top' or * 'bottom' (default). * {Function} groupOrder * A sorting function for ordering groups * {Boolean} stack * If true (deafult), items will be stacked on * top of each other. * {Number} margin.axis * Margin between the axis and the items in pixels. * Default is 20. * {Number} margin.item.horizontal * Horizontal margin between items in pixels. * Default is 10. * {Number} margin.item.vertical * Vertical Margin between items in pixels. * Default is 10. * {Number} margin.item * Margin between items in pixels in both horizontal * and vertical direction. Default is 10. * {Number} margin * Set margin for both axis and items in pixels. * {Number} padding * Padding of the contents of an item in pixels. * Must correspond with the items css. Default is 5. * {Boolean} selectable * If true (default), items can be selected. * {Boolean} editable * Set all editable options to true or false * {Boolean} editable.updateTime * Allow dragging an item to an other moment in time * {Boolean} editable.updateGroup * Allow dragging an item to an other group * {Boolean} editable.add * Allow creating new items on double tap * {Boolean} editable.remove * Allow removing items by clicking the delete button * top right of a selected item. * {Function(item: Item, callback: Function)} onAdd * Callback function triggered when an item is about to be added: * when the user double taps an empty space in the Timeline. * {Function(item: Item, callback: Function)} onUpdate * Callback function fired when an item is about to be updated. * This function typically has to show a dialog where the user * change the item. If not implemented, nothing happens. * {Function(item: Item, callback: Function)} onMove * Fired when an item has been moved. If not implemented, * the move action will be accepted. * {Function(item: Item, callback: Function)} onRemove * Fired when an item is about to be deleted. * If not implemented, the item will be always removed. */ ItemSet.prototype.setOptions = function(options) { if (options) { // copy all options that we know var fields = ['type', 'align', 'orientation', 'padding', 'stack', 'selectable', 'groupOrder']; util.selectiveExtend(fields, this.options, options); if ('margin' in options) { if (typeof options.margin === 'number') { this.options.margin.axis = options.margin; this.options.margin.item.horizontal = options.margin; this.options.margin.item.vertical = options.margin; } else if (typeof options.margin === 'object') { util.selectiveExtend(['axis'], this.options.margin, options.margin); if ('item' in options.margin) { if (typeof options.margin.item === 'number') { this.options.margin.item.horizontal = options.margin.item; this.options.margin.item.vertical = options.margin.item; } else if (typeof options.margin.item === 'object') { util.selectiveExtend(['horizontal', 'vertical'], this.options.margin.item, options.margin.item); } } } } if ('editable' in options) { if (typeof options.editable === 'boolean') { this.options.editable.updateTime = options.editable; this.options.editable.updateGroup = options.editable; this.options.editable.add = options.editable; this.options.editable.remove = options.editable; } else if (typeof options.editable === 'object') { util.selectiveExtend(['updateTime', 'updateGroup', 'add', 'remove'], this.options.editable, options.editable); } } // callback functions var addCallback = (function (name) { if (name in options) { var fn = options[name]; if (!(fn instanceof Function)) { throw new Error('option ' + name + ' must be a function ' + name + '(item, callback)'); } this.options[name] = fn; } }).bind(this); ['onAdd', 'onUpdate', 'onRemove', 'onMove'].forEach(addCallback); // force the itemSet to refresh: options like orientation and margins may be changed this.markDirty(); } }; /** * Mark the ItemSet dirty so it will refresh everything with next redraw */ ItemSet.prototype.markDirty = function() { this.groupIds = []; this.stackDirty = true; }; /** * Destroy the ItemSet */ ItemSet.prototype.destroy = function() { this.hide(); this.setItems(null); this.setGroups(null); this.hammer = null; this.body = null; this.conversion = null; }; /** * Hide the component from the DOM */ ItemSet.prototype.hide = function() { // remove the frame containing the items if (this.dom.frame.parentNode) { this.dom.frame.parentNode.removeChild(this.dom.frame); } // remove the axis with dots if (this.dom.axis.parentNode) { this.dom.axis.parentNode.removeChild(this.dom.axis); } // remove the labelset containing all group labels if (this.dom.labelSet.parentNode) { this.dom.labelSet.parentNode.removeChild(this.dom.labelSet); } }; /** * Show the component in the DOM (when not already visible). * @return {Boolean} changed */ ItemSet.prototype.show = function() { // show frame containing the items if (!this.dom.frame.parentNode) { this.body.dom.center.appendChild(this.dom.frame); } // show axis with dots if (!this.dom.axis.parentNode) { this.body.dom.backgroundVertical.appendChild(this.dom.axis); } // show labelset containing labels if (!this.dom.labelSet.parentNode) { this.body.dom.left.appendChild(this.dom.labelSet); } }; /** * Set selected items by their id. Replaces the current selection * Unknown id's are silently ignored. * @param {Array} [ids] An array with zero or more id's of the items to be * selected. If ids is an empty array, all items will be * unselected. */ ItemSet.prototype.setSelection = function(ids) { var i, ii, id, item; if (ids) { if (!Array.isArray(ids)) { throw new TypeError('Array expected'); } // unselect currently selected items for (i = 0, ii = this.selection.length; i < ii; i++) { id = this.selection[i]; item = this.items[id]; if (item) item.unselect(); } // select items this.selection = []; for (i = 0, ii = ids.length; i < ii; i++) { id = ids[i]; item = this.items[id]; if (item) { this.selection.push(id); item.select(); } } } }; /** * Get the selected items by their id * @return {Array} ids The ids of the selected items */ ItemSet.prototype.getSelection = function() { return this.selection.concat([]); }; /** * Get the id's of the currently visible items. * @returns {Array} The ids of the visible items */ ItemSet.prototype.getVisibleItems = function() { var range = this.body.range.getRange(); var left = this.body.util.toScreen(range.start); var right = this.body.util.toScreen(range.end); var ids = []; for (var groupId in this.groups) { if (this.groups.hasOwnProperty(groupId)) { var group = this.groups[groupId]; var rawVisibleItems = group.visibleItems; // filter the "raw" set with visibleItems into a set which is really // visible by pixels for (var i = 0; i < rawVisibleItems.length; i++) { var item = rawVisibleItems[i]; // TODO: also check whether visible vertically if ((item.left < right) && (item.left + item.width > left)) { ids.push(item.id); } } } } return ids; }; /** * Deselect a selected item * @param {String | Number} id * @private */ ItemSet.prototype._deselect = function(id) { var selection = this.selection; for (var i = 0, ii = selection.length; i < ii; i++) { if (selection[i] == id) { // non-strict comparison! selection.splice(i, 1); break; } } }; /** * Repaint the component * @return {boolean} Returns true if the component is resized */ ItemSet.prototype.redraw = function() { var margin = this.options.margin, range = this.body.range, asSize = util.option.asSize, options = this.options, orientation = options.orientation, resized = false, frame = this.dom.frame, editable = options.editable.updateTime || options.editable.updateGroup; // update class name frame.className = 'itemset' + (editable ? ' editable' : ''); // reorder the groups (if needed) resized = this._orderGroups() || resized; // check whether zoomed (in that case we need to re-stack everything) // TODO: would be nicer to get this as a trigger from Range var visibleInterval = range.end - range.start; var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.props.width != this.props.lastWidth); if (zoomed) this.stackDirty = true; this.lastVisibleInterval = visibleInterval; this.props.lastWidth = this.props.width; // redraw all groups var restack = this.stackDirty, firstGroup = this._firstGroup(), firstMargin = { item: margin.item, axis: margin.axis }, nonFirstMargin = { item: margin.item, axis: margin.item.vertical / 2 }, height = 0, minHeight = margin.axis + margin.item.vertical; util.forEach(this.groups, function (group) { var groupMargin = (group == firstGroup) ? firstMargin : nonFirstMargin; var groupResized = group.redraw(range, groupMargin, restack); resized = groupResized || resized; height += group.height; }); height = Math.max(height, minHeight); this.stackDirty = false; // update frame height frame.style.height = asSize(height); // calculate actual size and position this.props.top = frame.offsetTop; this.props.left = frame.offsetLeft; this.props.width = frame.offsetWidth; this.props.height = height; // reposition axis this.dom.axis.style.top = asSize((orientation == 'top') ? (this.body.domProps.top.height + this.body.domProps.border.top) : (this.body.domProps.top.height + this.body.domProps.centerContainer.height)); this.dom.axis.style.left = this.body.domProps.border.left + 'px'; // check if this component is resized resized = this._isResized() || resized; return resized; }; /** * Get the first group, aligned with the axis * @return {Group | null} firstGroup * @private */ ItemSet.prototype._firstGroup = function() { var firstGroupIndex = (this.options.orientation == 'top') ? 0 : (this.groupIds.length - 1); var firstGroupId = this.groupIds[firstGroupIndex]; var firstGroup = this.groups[firstGroupId] || this.groups[UNGROUPED]; return firstGroup || null; }; /** * Create or delete the group holding all ungrouped items. This group is used when * there are no groups specified. * @protected */ ItemSet.prototype._updateUngrouped = function() { var ungrouped = this.groups[UNGROUPED]; if (this.groupsData) { // remove the group holding all ungrouped items if (ungrouped) { ungrouped.hide(); delete this.groups[UNGROUPED]; } } else { // create a group holding all (unfiltered) items if (!ungrouped) { var id = null; var data = null; ungrouped = new Group(id, data, this); this.groups[UNGROUPED] = ungrouped; for (var itemId in this.items) { if (this.items.hasOwnProperty(itemId)) { ungrouped.add(this.items[itemId]); } } ungrouped.show(); } } }; /** * Get the element for the labelset * @return {HTMLElement} labelSet */ ItemSet.prototype.getLabelSet = function() { return this.dom.labelSet; }; /** * Set items * @param {vis.DataSet | null} items */ ItemSet.prototype.setItems = function(items) { var me = this, ids, oldItemsData = this.itemsData; // replace the dataset if (!items) { this.itemsData = null; } else if (items instanceof DataSet || items instanceof DataView) { this.itemsData = items; } else { throw new TypeError('Data must be an instance of DataSet or DataView'); } if (oldItemsData) { // unsubscribe from old dataset util.forEach(this.itemListeners, function (callback, event) { oldItemsData.off(event, callback); }); // remove all drawn items ids = oldItemsData.getIds(); this._onRemove(ids); } if (this.itemsData) { // subscribe to new dataset var id = this.id; util.forEach(this.itemListeners, function (callback, event) { me.itemsData.on(event, callback, id); }); // add all new items ids = this.itemsData.getIds(); this._onAdd(ids); // update the group holding all ungrouped items this._updateUngrouped(); } }; /** * Get the current items * @returns {vis.DataSet | null} */ ItemSet.prototype.getItems = function() { return this.itemsData; }; /** * Set groups * @param {vis.DataSet} groups */ ItemSet.prototype.setGroups = function(groups) { var me = this, ids; // unsubscribe from current dataset if (this.groupsData) { util.forEach(this.groupListeners, function (callback, event) { me.groupsData.unsubscribe(event, callback); }); // remove all drawn groups ids = this.groupsData.getIds(); this.groupsData = null; this._onRemoveGroups(ids); // note: this will cause a redraw } // replace the dataset if (!groups) { this.groupsData = null; } else if (groups instanceof DataSet || groups instanceof DataView) { this.groupsData = groups; } else { throw new TypeError('Data must be an instance of DataSet or DataView'); } if (this.groupsData) { // subscribe to new dataset var id = this.id; util.forEach(this.groupListeners, function (callback, event) { me.groupsData.on(event, callback, id); }); // draw all ms ids = this.groupsData.getIds(); this._onAddGroups(ids); } // update the group holding all ungrouped items this._updateUngrouped(); // update the order of all items in each group this._order(); this.body.emitter.emit('change'); }; /** * Get the current groups * @returns {vis.DataSet | null} groups */ ItemSet.prototype.getGroups = function() { return this.groupsData; }; /** * Remove an item by its id * @param {String | Number} id */ ItemSet.prototype.removeItem = function(id) { var item = this.itemsData.get(id), dataset = this.itemsData.getDataSet(); if (item) { // confirm deletion this.options.onRemove(item, function (item) { if (item) { // remove by id here, it is possible that an item has no id defined // itself, so better not delete by the item itself dataset.remove(id); } }); } }; /** * Handle updated items * @param {Number[]} ids * @protected */ ItemSet.prototype._onUpdate = function(ids) { var me = this; ids.forEach(function (id) { var itemData = me.itemsData.get(id, me.itemOptions), item = me.items[id], type = itemData.type || me.options.type || (itemData.end ? 'range' : 'box'); var constructor = ItemSet.types[type]; if (item) { // update item if (!constructor || !(item instanceof constructor)) { // item type has changed, delete the item and recreate it me._removeItem(item); item = null; } else { me._updateItem(item, itemData); } } if (!item) { // create item if (constructor) { item = new constructor(itemData, me.conversion, me.options); item.id = id; // TODO: not so nice setting id afterwards me._addItem(item); } else if (type == 'rangeoverflow') { // TODO: deprecated since version 2.1.0 (or 3.0.0?). cleanup some day throw new TypeError('Item type "rangeoverflow" is deprecated. Use css styling instead: ' + '.vis.timeline .item.range .content {overflow: visible;}'); } else { throw new TypeError('Unknown item type "' + type + '"'); } } }); this._order(); this.stackDirty = true; // force re-stacking of all items next redraw this.body.emitter.emit('change'); }; /** * Handle added items * @param {Number[]} ids * @protected */ ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate; /** * Handle removed items * @param {Number[]} ids * @protected */ ItemSet.prototype._onRemove = function(ids) { var count = 0; var me = this; ids.forEach(function (id) { var item = me.items[id]; if (item) { count++; me._removeItem(item); } }); if (count) { // update order this._order(); this.stackDirty = true; // force re-stacking of all items next redraw this.body.emitter.emit('change'); } }; /** * Update the order of item in all groups * @private */ ItemSet.prototype._order = function() { // reorder the items in all groups // TODO: optimization: only reorder groups affected by the changed items util.forEach(this.groups, function (group) { group.order(); }); }; /** * Handle updated groups * @param {Number[]} ids * @private */ ItemSet.prototype._onUpdateGroups = function(ids) { this._onAddGroups(ids); }; /** * Handle changed groups * @param {Number[]} ids * @private */ ItemSet.prototype._onAddGroups = function(ids) { var me = this; ids.forEach(function (id) { var groupData = me.groupsData.get(id); var group = me.groups[id]; if (!group) { // check for reserved ids if (id == UNGROUPED) { throw new Error('Illegal group id. ' + id + ' is a reserved id.'); } var groupOptions = Object.create(me.options); util.extend(groupOptions, { height: null }); group = new Group(id, groupData, me); me.groups[id] = group; // add items with this groupId to the new group for (var itemId in me.items) { if (me.items.hasOwnProperty(itemId)) { var item = me.items[itemId]; if (item.data.group == id) { group.add(item); } } } group.order(); group.show(); } else { // update group group.setData(groupData); } }); this.body.emitter.emit('change'); }; /** * Handle removed groups * @param {Number[]} ids * @private */ ItemSet.prototype._onRemoveGroups = function(ids) { var groups = this.groups; ids.forEach(function (id) { var group = groups[id]; if (group) { group.hide(); delete groups[id]; } }); this.markDirty(); this.body.emitter.emit('change'); }; /** * Reorder the groups if needed * @return {boolean} changed * @private */ ItemSet.prototype._orderGroups = function () { if (this.groupsData) { // reorder the groups var groupIds = this.groupsData.getIds({ order: this.options.groupOrder }); var changed = !util.equalArray(groupIds, this.groupIds); if (changed) { // hide all groups, removes them from the DOM var groups = this.groups; groupIds.forEach(function (groupId) { groups[groupId].hide(); }); // show the groups again, attach them to the DOM in correct order groupIds.forEach(function (groupId) { groups[groupId].show(); }); this.groupIds = groupIds; } return changed; } else { return false; } }; /** * Add a new item * @param {Item} item * @private */ ItemSet.prototype._addItem = function(item) { this.items[item.id] = item; // add to group var groupId = this.groupsData ? item.data.group : UNGROUPED; var group = this.groups[groupId]; if (group) group.add(item); }; /** * Update an existing item * @param {Item} item * @param {Object} itemData * @private */ ItemSet.prototype._updateItem = function(item, itemData) { var oldGroupId = item.data.group; item.data = itemData; if (item.displayed) { item.redraw(); } // update group if (oldGroupId != item.data.group) { var oldGroup = this.groups[oldGroupId]; if (oldGroup) oldGroup.remove(item); var groupId = this.groupsData ? item.data.group : UNGROUPED; var group = this.groups[groupId]; if (group) group.add(item); } }; /** * Delete an item from the ItemSet: remove it from the DOM, from the map * with items, and from the map with visible items, and from the selection * @param {Item} item * @private */ ItemSet.prototype._removeItem = function(item) { // remove from DOM item.hide(); // remove from items delete this.items[item.id]; // remove from selection var index = this.selection.indexOf(item.id); if (index != -1) this.selection.splice(index, 1); // remove from group var groupId = this.groupsData ? item.data.group : UNGROUPED; var group = this.groups[groupId]; if (group) group.remove(item); }; /** * Create an array containing all items being a range (having an end date) * @param array * @returns {Array} * @private */ ItemSet.prototype._constructByEndArray = function(array) { var endArray = []; for (var i = 0; i < array.length; i++) { if (array[i] instanceof ItemRange) { endArray.push(array[i]); } } return endArray; }; /** * Register the clicked item on touch, before dragStart is initiated. * * dragStart is initiated from a mousemove event, which can have left the item * already resulting in an item == null * * @param {Event} event * @private */ ItemSet.prototype._onTouch = function (event) { // store the touched item, used in _onDragStart this.touchParams.item = ItemSet.itemFromTarget(event); }; /** * Start dragging the selected events * @param {Event} event * @private */ ItemSet.prototype._onDragStart = function (event) { if (!this.options.editable.updateTime && !this.options.editable.updateGroup) { return; } var item = this.touchParams.item || null, me = this, props; if (item && item.selected) { var dragLeftItem = event.target.dragLeftItem; var dragRightItem = event.target.dragRightItem; if (dragLeftItem) { props = { item: dragLeftItem }; if (me.options.editable.updateTime) { props.start = item.data.start.valueOf(); } if (me.options.editable.updateGroup) { if ('group' in item.data) props.group = item.data.group; } this.touchParams.itemProps = [props]; } else if (dragRightItem) { props = { item: dragRightItem }; if (me.options.editable.updateTime) { props.end = item.data.end.valueOf(); } if (me.options.editable.updateGroup) { if ('group' in item.data) props.group = item.data.group; } this.touchParams.itemProps = [props]; } else { this.touchParams.itemProps = this.getSelection().map(function (id) { var item = me.items[id]; var props = { item: item }; if (me.options.editable.updateTime) { if ('start' in item.data) props.start = item.data.start.valueOf(); if ('end' in item.data) props.end = item.data.end.valueOf(); } if (me.options.editable.updateGroup) { if ('group' in item.data) props.group = item.data.group; } return props; }); } event.stopPropagation(); } }; /** * Drag selected items * @param {Event} event * @private */ ItemSet.prototype._onDrag = function (event) { if (this.touchParams.itemProps) { var range = this.body.range, snap = this.body.util.snap || null, deltaX = event.gesture.deltaX, scale = (this.props.width / (range.end - range.start)), offset = deltaX / scale; // move this.touchParams.itemProps.forEach(function (props) { if ('start' in props) { var start = new Date(props.start + offset); props.item.data.start = snap ? snap(start) : start; } if ('end' in props) { var end = new Date(props.end + offset); props.item.data.end = snap ? snap(end) : end; } if ('group' in props) { // drag from one group to another var group = ItemSet.groupFromTarget(event); if (group && group.groupId != props.item.data.group) { var oldGroup = props.item.parent; oldGroup.remove(props.item); oldGroup.order(); group.add(props.item); group.order(); props.item.data.group = group.groupId; } } }); // TODO: implement onMoving handler this.stackDirty = true; // force re-stacking of all items next redraw this.body.emitter.emit('change'); event.stopPropagation(); } }; /** * End of dragging selected items * @param {Event} event * @private */ ItemSet.prototype._onDragEnd = function (event) { if (this.touchParams.itemProps) { // prepare a change set for the changed items var changes = [], me = this, dataset = this.itemsData.getDataSet(); this.touchParams.itemProps.forEach(function (props) { var id = props.item.id, itemData = me.itemsData.get(id, me.itemOptions); var changed = false; if ('start' in props.item.data) { changed = (props.start != props.item.data.start.valueOf()); itemData.start = util.convert(props.item.data.start, dataset._options.type && dataset._options.type.start || 'Date'); } if ('end' in props.item.data) { changed = changed || (props.end != props.item.data.end.valueOf()); itemData.end = util.convert(props.item.data.end, dataset._options.type && dataset._options.type.end || 'Date'); } if ('group' in props.item.data) { changed = changed || (props.group != props.item.data.group); itemData.group = props.item.data.group; } // only apply changes when start or end is actually changed if (changed) { me.options.onMove(itemData, function (itemData) { if (itemData) { // apply changes itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined) changes.push(itemData); } else { // restore original values if ('start' in props) props.item.data.start = props.start; if ('end' in props) props.item.data.end = props.end; me.stackDirty = true; // force re-stacking of all items next redraw me.body.emitter.emit('change'); } }); } }); this.touchParams.itemProps = null; // apply the changes to the data (if there are changes) if (changes.length) { dataset.update(changes); } event.stopPropagation(); } }; /** * Handle selecting/deselecting an item when tapping it * @param {Event} event * @private */ ItemSet.prototype._onSelectItem = function (event) { if (!this.options.selectable) return; var ctrlKey = event.gesture.srcEvent && event.gesture.srcEvent.ctrlKey; var shiftKey = event.gesture.srcEvent && event.gesture.srcEvent.shiftKey; if (ctrlKey || shiftKey) { this._onMultiSelectItem(event); return; } var oldSelection = this.getSelection(); var item = ItemSet.itemFromTarget(event); var selection = item ? [item.id] : []; this.setSelection(selection); var newSelection = this.getSelection(); // emit a select event, // except when old selection is empty and new selection is still empty if (newSelection.length > 0 || oldSelection.length > 0) { this.body.emitter.emit('select', { items: this.getSelection() }); } event.stopPropagation(); }; /** * Handle creation and updates of an item on double tap * @param event * @private */ ItemSet.prototype._onAddItem = function (event) { if (!this.options.selectable) return; if (!this.options.editable.add) return; var me = this, snap = this.body.util.snap || null, item = ItemSet.itemFromTarget(event); if (item) { // update item // execute async handler to update the item (or cancel it) var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset this.options.onUpdate(itemData, function (itemData) { if (itemData) { me.itemsData.update(itemData); } }); } else { // add item var xAbs = util.getAbsoluteLeft(this.dom.frame); var x = event.gesture.center.pageX - xAbs; var start = this.body.util.toTime(x); var newItem = { start: snap ? snap(start) : start, content: 'new item' }; // when default type is a range, add a default end date to the new item if (this.options.type === 'range') { var end = this.body.util.toTime(x + this.props.width / 5); newItem.end = snap ? snap(end) : end; } newItem[this.itemsData.fieldId] = util.randomUUID(); var group = ItemSet.groupFromTarget(event); if (group) { newItem.group = group.groupId; } // execute async handler to customize (or cancel) adding an item this.options.onAdd(newItem, function (item) { if (item) { me.itemsData.add(newItem); // TODO: need to trigger a redraw? } }); } }; /** * Handle selecting/deselecting multiple items when holding an item * @param {Event} event * @private */ ItemSet.prototype._onMultiSelectItem = function (event) { if (!this.options.selectable) return; var selection, item = ItemSet.itemFromTarget(event); if (item) { // multi select items selection = this.getSelection(); // current selection var index = selection.indexOf(item.id); if (index == -1) { // item is not yet selected -> select it selection.push(item.id); } else { // item is already selected -> deselect it selection.splice(index, 1); } this.setSelection(selection); this.body.emitter.emit('select', { items: this.getSelection() }); event.stopPropagation(); } }; /** * Find an item from an event target: * searches for the attribute 'timeline-item' in the event target's element tree * @param {Event} event * @return {Item | null} item */ ItemSet.itemFromTarget = function(event) { var target = event.target; while (target) { if (target.hasOwnProperty('timeline-item')) { return target['timeline-item']; } target = target.parentNode; } return null; }; /** * Find the Group from an event target: * searches for the attribute 'timeline-group' in the event target's element tree * @param {Event} event * @return {Group | null} group */ ItemSet.groupFromTarget = function(event) { var target = event.target; while (target) { if (target.hasOwnProperty('timeline-group')) { return target['timeline-group']; } target = target.parentNode; } return null; }; /** * Find the ItemSet from an event target: * searches for the attribute 'timeline-itemset' in the event target's element tree * @param {Event} event * @return {ItemSet | null} item */ ItemSet.itemSetFromTarget = function(event) { var target = event.target; while (target) { if (target.hasOwnProperty('timeline-itemset')) { return target['timeline-itemset']; } target = target.parentNode; } return null; }; module.exports = ItemSet; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var DOMutil = __webpack_require__(2); var Component = __webpack_require__(18); /** * Legend for Graph2d */ function Legend(body, options, side) { this.body = body; this.defaultOptions = { enabled: true, icons: true, iconSize: 20, iconSpacing: 6, left: { visible: true, position: 'top-left' // top/bottom - left,center,right }, right: { visible: true, position: 'top-left' // top/bottom - left,center,right } } this.side = side; this.options = util.extend({},this.defaultOptions); this.svgElements = {}; this.dom = {}; this.groups = {}; this.amountOfGroups = 0; this._create(); this.setOptions(options); } Legend.prototype = new Component(); Legend.prototype.addGroup = function(label, graphOptions) { if (!this.groups.hasOwnProperty(label)) { this.groups[label] = graphOptions; } this.amountOfGroups += 1; }; Legend.prototype.updateGroup = function(label, graphOptions) { this.groups[label] = graphOptions; }; Legend.prototype.removeGroup = function(label) { if (this.groups.hasOwnProperty(label)) { delete this.groups[label]; this.amountOfGroups -= 1; } }; Legend.prototype._create = function() { this.dom.frame = document.createElement('div'); this.dom.frame.className = 'legend'; this.dom.frame.style.position = "absolute"; this.dom.frame.style.top = "10px"; this.dom.frame.style.display = "block"; this.dom.textArea = document.createElement('div'); this.dom.textArea.className = 'legendText'; this.dom.textArea.style.position = "relative"; this.dom.textArea.style.top = "0px"; this.svg = document.createElementNS('http://www.w3.org/2000/svg',"svg"); this.svg.style.position = 'absolute'; this.svg.style.top = 0 +'px'; this.svg.style.width = this.options.iconSize + 5 + 'px'; this.dom.frame.appendChild(this.svg); this.dom.frame.appendChild(this.dom.textArea); }; /** * Hide the component from the DOM */ Legend.prototype.hide = function() { // remove the frame containing the items if (this.dom.frame.parentNode) { this.dom.frame.parentNode.removeChild(this.dom.frame); } }; /** * Show the component in the DOM (when not already visible). * @return {Boolean} changed */ Legend.prototype.show = function() { // show frame containing the items if (!this.dom.frame.parentNode) { this.body.dom.center.appendChild(this.dom.frame); } }; Legend.prototype.setOptions = function(options) { var fields = ['enabled','orientation','icons','left','right']; util.selectiveDeepExtend(fields, this.options, options); }; Legend.prototype.redraw = function() { var activeGroups = 0; for (var groupId in this.groups) { if (this.groups.hasOwnProperty(groupId)) { if (this.groups[groupId].visible == true) { activeGroups++; } } } if (this.options[this.side].visible == false || this.amountOfGroups == 0 || this.options.enabled == false || activeGroups == 0) { this.hide(); } else { this.show(); if (this.options[this.side].position == 'top-left' || this.options[this.side].position == 'bottom-left') { this.dom.frame.style.left = '4px'; this.dom.frame.style.textAlign = "left"; this.dom.textArea.style.textAlign = "left"; this.dom.textArea.style.left = (this.options.iconSize + 15) + 'px'; this.dom.textArea.style.right = ''; this.svg.style.left = 0 +'px'; this.svg.style.right = ''; } else { this.dom.frame.style.right = '4px'; this.dom.frame.style.textAlign = "right"; this.dom.textArea.style.textAlign = "right"; this.dom.textArea.style.right = (this.options.iconSize + 15) + 'px'; this.dom.textArea.style.left = ''; this.svg.style.right = 0 +'px'; this.svg.style.left = ''; } if (this.options[this.side].position == 'top-left' || this.options[this.side].position == 'top-right') { this.dom.frame.style.top = 4 - Number(this.body.dom.center.style.top.replace("px","")) + 'px'; this.dom.frame.style.bottom = ''; } else { this.dom.frame.style.bottom = 4 - Number(this.body.dom.center.style.top.replace("px","")) + 'px'; this.dom.frame.style.top = ''; } if (this.options.icons == false) { this.dom.frame.style.width = this.dom.textArea.offsetWidth + 10 + 'px'; this.dom.textArea.style.right = ''; this.dom.textArea.style.left = ''; this.svg.style.width = '0px'; } else { this.dom.frame.style.width = this.options.iconSize + 15 + this.dom.textArea.offsetWidth + 10 + 'px' this.drawLegendIcons(); } var content = ''; for (var groupId in this.groups) { if (this.groups.hasOwnProperty(groupId)) { if (this.groups[groupId].visible == true) { content += this.groups[groupId].content + '<br />'; } } } this.dom.textArea.innerHTML = content; this.dom.textArea.style.lineHeight = ((0.75 * this.options.iconSize) + this.options.iconSpacing) + 'px'; } }; Legend.prototype.drawLegendIcons = function() { if (this.dom.frame.parentNode) { DOMutil.prepareElements(this.svgElements); var padding = window.getComputedStyle(this.dom.frame).paddingTop; var iconOffset = Number(padding.replace('px','')); var x = iconOffset; var iconWidth = this.options.iconSize; var iconHeight = 0.75 * this.options.iconSize; var y = iconOffset + 0.5 * iconHeight + 3; this.svg.style.width = iconWidth + 5 + iconOffset + 'px'; for (var groupId in this.groups) { if (this.groups.hasOwnProperty(groupId)) { if (this.groups[groupId].visible == true) { this.groups[groupId].drawIcon(x, y, this.svgElements, this.svg, iconWidth, iconHeight); y += iconHeight + this.options.iconSpacing; } } } DOMutil.cleanupElements(this.svgElements); } }; module.exports = Legend; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var DOMutil = __webpack_require__(2); var DataSet = __webpack_require__(3); var DataView = __webpack_require__(4); var Component = __webpack_require__(18); var DataAxis = __webpack_require__(21); var GraphGroup = __webpack_require__(22); var Legend = __webpack_require__(25); var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items /** * This is the constructor of the LineGraph. It requires a Timeline body and options. * * @param body * @param options * @constructor */ function LineGraph(body, options) { this.id = util.randomUUID(); this.body = body; this.defaultOptions = { yAxisOrientation: 'left', defaultGroup: 'default', sort: true, sampling: true, graphHeight: '400px', shaded: { enabled: false, orientation: 'bottom' // top, bottom }, style: 'line', // line, bar barChart: { width: 50, align: 'center' // left, center, right }, catmullRom: { enabled: true, parametrization: 'centripetal', // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5) alpha: 0.5 }, drawPoints: { enabled: true, size: 6, style: 'square' // square, circle }, dataAxis: { showMinorLabels: true, showMajorLabels: true, icons: false, width: '40px', visible: true }, legend: { enabled: false, icons: true, left: { visible: true, position: 'top-left' // top/bottom - left,right }, right: { visible: true, position: 'top-right' // top/bottom - left,right } } }; // options is shared by this ItemSet and all its items this.options = util.extend({}, this.defaultOptions); this.dom = {}; this.props = {}; this.hammer = null; this.groups = {}; var me = this; this.itemsData = null; // DataSet this.groupsData = null; // DataSet // listeners for the DataSet of the items this.itemListeners = { 'add': function (event, params, senderId) { me._onAdd(params.items); }, 'update': function (event, params, senderId) { me._onUpdate(params.items); }, 'remove': function (event, params, senderId) { me._onRemove(params.items); } }; // listeners for the DataSet of the groups this.groupListeners = { 'add': function (event, params, senderId) { me._onAddGroups(params.items); }, 'update': function (event, params, senderId) { me._onUpdateGroups(params.items); }, 'remove': function (event, params, senderId) { me._onRemoveGroups(params.items); } }; this.items = {}; // object with an Item for every data item this.selection = []; // list with the ids of all selected nodes this.lastStart = this.body.range.start; this.touchParams = {}; // stores properties while dragging this.svgElements = {}; this.setOptions(options); this.groupsUsingDefaultStyles = [0]; this.body.emitter.on("rangechange",function() { if (me.lastStart != 0) { var offset = me.body.range.start - me.lastStart; var range = me.body.range.end - me.body.range.start; if (me.width != 0) { var rangePerPixelInv = me.width/range; var xOffset = offset * rangePerPixelInv; me.svg.style.left = (-me.width - xOffset) + "px"; } } }); this.body.emitter.on("rangechanged", function() { me.lastStart = me.body.range.start; me.svg.style.left = util.option.asSize(-me.width); me._updateGraph.apply(me); }); // create the HTML DOM this._create(); this.body.emitter.emit("change"); } LineGraph.prototype = new Component(); /** * Create the HTML DOM for the ItemSet */ LineGraph.prototype._create = function(){ var frame = document.createElement('div'); frame.className = 'LineGraph'; this.dom.frame = frame; // create svg element for graph drawing. this.svg = document.createElementNS('http://www.w3.org/2000/svg',"svg"); this.svg.style.position = "relative"; this.svg.style.height = ('' + this.options.graphHeight).replace("px",'') + 'px'; this.svg.style.display = "block"; frame.appendChild(this.svg); // data axis this.options.dataAxis.orientation = 'left'; this.yAxisLeft = new DataAxis(this.body, this.options.dataAxis, this.svg); this.options.dataAxis.orientation = 'right'; this.yAxisRight = new DataAxis(this.body, this.options.dataAxis, this.svg); delete this.options.dataAxis.orientation; // legends this.legendLeft = new Legend(this.body, this.options.legend, 'left'); this.legendRight = new Legend(this.body, this.options.legend, 'right'); this.show(); }; /** * set the options of the LineGraph. the mergeOptions is used for subObjects that have an enabled element. * @param options */ LineGraph.prototype.setOptions = function(options) { if (options) { var fields = ['sampling','defaultGroup','graphHeight','yAxisOrientation','style','barChart','dataAxis','sort']; util.selectiveDeepExtend(fields, this.options, options); util.mergeOptions(this.options, options,'catmullRom'); util.mergeOptions(this.options, options,'drawPoints'); util.mergeOptions(this.options, options,'shaded'); util.mergeOptions(this.options, options,'legend'); if (options.catmullRom) { if (typeof options.catmullRom == 'object') { if (options.catmullRom.parametrization) { if (options.catmullRom.parametrization == 'uniform') { this.options.catmullRom.alpha = 0; } else if (options.catmullRom.parametrization == 'chordal') { this.options.catmullRom.alpha = 1.0; } else { this.options.catmullRom.parametrization = 'centripetal'; this.options.catmullRom.alpha = 0.5; } } } } if (this.yAxisLeft) { if (options.dataAxis !== undefined) { this.yAxisLeft.setOptions(this.options.dataAxis); this.yAxisRight.setOptions(this.options.dataAxis); } } if (this.legendLeft) { if (options.legend !== undefined) { this.legendLeft.setOptions(this.options.legend); this.legendRight.setOptions(this.options.legend); } } if (this.groups.hasOwnProperty(UNGROUPED)) { this.groups[UNGROUPED].setOptions(options); } } if (this.dom.frame) { this._updateGraph(); } }; /** * Hide the component from the DOM */ LineGraph.prototype.hide = function() { // remove the frame containing the items if (this.dom.frame.parentNode) { this.dom.frame.parentNode.removeChild(this.dom.frame); } }; /** * Show the component in the DOM (when not already visible). * @return {Boolean} changed */ LineGraph.prototype.show = function() { // show frame containing the items if (!this.dom.frame.parentNode) { this.body.dom.center.appendChild(this.dom.frame); } }; /** * Set items * @param {vis.DataSet | null} items */ LineGraph.prototype.setItems = function(items) { var me = this, ids, oldItemsData = this.itemsData; // replace the dataset if (!items) { this.itemsData = null; } else if (items instanceof DataSet || items instanceof DataView) { this.itemsData = items; } else { throw new TypeError('Data must be an instance of DataSet or DataView'); } if (oldItemsData) { // unsubscribe from old dataset util.forEach(this.itemListeners, function (callback, event) { oldItemsData.off(event, callback); }); // remove all drawn items ids = oldItemsData.getIds(); this._onRemove(ids); } if (this.itemsData) { // subscribe to new dataset var id = this.id; util.forEach(this.itemListeners, function (callback, event) { me.itemsData.on(event, callback, id); }); // add all new items ids = this.itemsData.getIds(); this._onAdd(ids); } this._updateUngrouped(); this._updateGraph(); this.redraw(); }; /** * Set groups * @param {vis.DataSet} groups */ LineGraph.prototype.setGroups = function(groups) { var me = this, ids; // unsubscribe from current dataset if (this.groupsData) { util.forEach(this.groupListeners, function (callback, event) { me.groupsData.unsubscribe(event, callback); }); // remove all drawn groups ids = this.groupsData.getIds(); this.groupsData = null; this._onRemoveGroups(ids); // note: this will cause a redraw } // replace the dataset if (!groups) { this.groupsData = null; } else if (groups instanceof DataSet || groups instanceof DataView) { this.groupsData = groups; } else { throw new TypeError('Data must be an instance of DataSet or DataView'); } if (this.groupsData) { // subscribe to new dataset var id = this.id; util.forEach(this.groupListeners, function (callback, event) { me.groupsData.on(event, callback, id); }); // draw all ms ids = this.groupsData.getIds(); this._onAddGroups(ids); } this._onUpdate(); }; LineGraph.prototype._onUpdate = function(ids) { this._updateUngrouped(); this._updateAllGroupData(); this._updateGraph(); this.redraw(); }; LineGraph.prototype._onAdd = function (ids) {this._onUpdate(ids);}; LineGraph.prototype._onRemove = function (ids) {this._onUpdate(ids);}; LineGraph.prototype._onUpdateGroups = function (groupIds) { for (var i = 0; i < groupIds.length; i++) { var group = this.groupsData.get(groupIds[i]); this._updateGroup(group, groupIds[i]); } this._updateGraph(); this.redraw(); }; LineGraph.prototype._onAddGroups = function (groupIds) {this._onUpdateGroups(groupIds);}; LineGraph.prototype._onRemoveGroups = function (groupIds) { for (var i = 0; i < groupIds.length; i++) { if (!this.groups.hasOwnProperty(groupIds[i])) { if (this.groups[groupIds[i]].options.yAxisOrientation == 'right') { this.yAxisRight.removeGroup(groupIds[i]); this.legendRight.removeGroup(groupIds[i]); this.legendRight.redraw(); } else { this.yAxisLeft.removeGroup(groupIds[i]); this.legendLeft.removeGroup(groupIds[i]); this.legendLeft.redraw(); } delete this.groups[groupIds[i]]; } } this._updateUngrouped(); this._updateGraph(); this.redraw(); }; /** * update a group object * * @param group * @param groupId * @private */ LineGraph.prototype._updateGroup = function (group, groupId) { if (!this.groups.hasOwnProperty(groupId)) { this.groups[groupId] = new GraphGroup(group, groupId, this.options, this.groupsUsingDefaultStyles); if (this.groups[groupId].options.yAxisOrientation == 'right') { this.yAxisRight.addGroup(groupId, this.groups[groupId]); this.legendRight.addGroup(groupId, this.groups[groupId]); } else { this.yAxisLeft.addGroup(groupId, this.groups[groupId]); this.legendLeft.addGroup(groupId, this.groups[groupId]); } } else { this.groups[groupId].update(group); if (this.groups[groupId].options.yAxisOrientation == 'right') { this.yAxisRight.updateGroup(groupId, this.groups[groupId]); this.legendRight.updateGroup(groupId, this.groups[groupId]); } else { this.yAxisLeft.updateGroup(groupId, this.groups[groupId]); this.legendLeft.updateGroup(groupId, this.groups[groupId]); } } this.legendLeft.redraw(); this.legendRight.redraw(); }; LineGraph.prototype._updateAllGroupData = function () { if (this.itemsData != null) { var groupsContent = {}; for (var groupId in this.groups) { if (this.groups.hasOwnProperty(groupId)) { groupsContent[groupId] = []; } } for (var itemId in this.itemsData._data) { if (this.itemsData._data.hasOwnProperty(itemId)) { var item = this.itemsData._data[itemId]; item.x = util.convert(item.x,"Date"); groupsContent[item.group].push(item); } } for (var groupId in this.groups) { if (this.groups.hasOwnProperty(groupId)) { this.groups[groupId].setItems(groupsContent[groupId]); } } } }; /** * Create or delete the group holding all ungrouped items. This group is used when * there are no groups specified. This anonymous group is called 'graph'. * @protected */ LineGraph.prototype._updateUngrouped = function() { if (this.itemsData != null) { // var t0 = new Date(); var group = {id: UNGROUPED, content: this.options.defaultGroup}; this._updateGroup(group, UNGROUPED); var ungroupedCounter = 0; if (this.itemsData) { for (var itemId in this.itemsData._data) { if (this.itemsData._data.hasOwnProperty(itemId)) { var item = this.itemsData._data[itemId]; if (item != undefined) { if (item.hasOwnProperty('group')) { if (item.group === undefined) { item.group = UNGROUPED; } } else { item.group = UNGROUPED; } ungroupedCounter = item.group == UNGROUPED ? ungroupedCounter + 1 : ungroupedCounter; } } } } // much much slower // var datapoints = this.itemsData.get({ // filter: function (item) {return item.group === undefined;}, // showInternalIds:true // }); // if (datapoints.length > 0) { // var updateQuery = []; // for (var i = 0; i < datapoints.length; i++) { // updateQuery.push({id:datapoints[i].id, group: UNGROUPED}); // } // this.itemsData.update(updateQuery, true); // } // var t1 = new Date(); // var pointInUNGROUPED = this.itemsData.get({filter: function (item) {return item.group == UNGROUPED;}}); if (ungroupedCounter == 0) { delete this.groups[UNGROUPED]; this.legendLeft.removeGroup(UNGROUPED); this.legendRight.removeGroup(UNGROUPED); this.yAxisLeft.removeGroup(UNGROUPED); this.yAxisRight.removeGroup(UNGROUPED); } // console.log("getting amount ungrouped",new Date() - t1); // console.log("putting in ungrouped",new Date() - t0); } else { delete this.groups[UNGROUPED]; this.legendLeft.removeGroup(UNGROUPED); this.legendRight.removeGroup(UNGROUPED); this.yAxisLeft.removeGroup(UNGROUPED); this.yAxisRight.removeGroup(UNGROUPED); } this.legendLeft.redraw(); this.legendRight.redraw(); }; /** * Redraw the component, mandatory function * @return {boolean} Returns true if the component is resized */ LineGraph.prototype.redraw = function() { var resized = false; this.svg.style.height = ('' + this.options.graphHeight).replace('px','') + 'px'; if (this.lastWidth === undefined && this.width || this.lastWidth != this.width) { resized = true; } // check if this component is resized resized = this._isResized() || resized; // check whether zoomed (in that case we need to re-stack everything) var visibleInterval = this.body.range.end - this.body.range.start; var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.width != this.lastWidth); this.lastVisibleInterval = visibleInterval; this.lastWidth = this.width; // calculate actual size and position this.width = this.dom.frame.offsetWidth; // the svg element is three times as big as the width, this allows for fully dragging left and right // without reloading the graph. the controls for this are bound to events in the constructor if (resized == true) { this.svg.style.width = util.option.asSize(3*this.width); this.svg.style.left = util.option.asSize(-this.width); } if (zoomed == true) { this._updateGraph(); } this.legendLeft.redraw(); this.legendRight.redraw(); return resized; }; /** * Update and redraw the graph. * */ LineGraph.prototype._updateGraph = function () { // reset the svg elements DOMutil.prepareElements(this.svgElements); if (this.width != 0 && this.itemsData != null) { var group, groupData, preprocessedGroup, i; var preprocessedGroupData = []; var processedGroupData = []; var groupRanges = []; var changeCalled = false; // getting group Ids var groupIds = []; for (var groupId in this.groups) { if (this.groups.hasOwnProperty(groupId)) { groupIds.push(groupId); } } // this is the range of the SVG canvas var minDate = this.body.util.toGlobalTime(- this.body.domProps.root.width); var maxDate = this.body.util.toGlobalTime(2 * this.body.domProps.root.width); // first select and preprocess the data from the datasets. // the groups have their preselection of data, we now loop over this data to see // what data we need to draw. Sorted data is much faster. // more optimization is possible by doing the sampling before and using the binary search // to find the end date to determine the increment. if (groupIds.length > 0) { for (i = 0; i < groupIds.length; i++) { group = this.groups[groupIds[i]]; if (group.visible == true) { groupData = []; // optimization for sorted data if (group.options.sort == true) { var guess = Math.max(0,util.binarySearchGeneric(group.itemsData, minDate, 'x', 'before')); for (var j = guess; j < group.itemsData.length; j++) { var item = group.itemsData[j]; if (item !== undefined) { if (item.x > maxDate) { groupData.push(item); break; } else { groupData.push(item); } } } } else { for (var j = 0; j < group.itemsData.length; j++) { var item = group.itemsData[j]; if (item !== undefined) { if (item.x > minDate && item.x < maxDate) { groupData.push(item); } } } } // preprocess, split into ranges and data if (groupData.length > 0) { preprocessedGroup = this._preprocessData(groupData, group); groupRanges.push({min: preprocessedGroup.min, max: preprocessedGroup.max}); preprocessedGroupData.push(preprocessedGroup.data); } else { groupRanges.push({}); preprocessedGroupData.push([]); } } else { groupRanges.push({}); preprocessedGroupData.push([]); } } // update the Y axis first, we use this data to draw at the correct Y points // changeCalled is required to clean the SVG on a change emit. changeCalled = this._updateYAxis(groupIds, groupRanges); if (changeCalled == true) { DOMutil.cleanupElements(this.svgElements); this.body.emitter.emit("change"); return; } // with the yAxis scaled correctly, use this to get the Y values of the points. for (i = 0; i < groupIds.length; i++) { group = this.groups[groupIds[i]]; processedGroupData.push(this._convertYvalues(preprocessedGroupData[i],group)) } // draw the groups for (i = 0; i < groupIds.length; i++) { group = this.groups[groupIds[i]]; if (group.visible == true) { if (group.options.style == 'line') { this._drawLineGraph(processedGroupData[i], group); } else { this._drawBarGraph (processedGroupData[i], group); } } } } } // cleanup unused svg elements DOMutil.cleanupElements(this.svgElements); }; /** * this sets the Y ranges for the Y axis. It also determines which of the axis should be shown or hidden. * @param {array} groupIds * @private */ LineGraph.prototype._updateYAxis = function (groupIds, groupRanges) { var changeCalled = false; var yAxisLeftUsed = false; var yAxisRightUsed = false; var minLeft = 1e9, minRight = 1e9, maxLeft = -1e9, maxRight = -1e9, minVal, maxVal; var orientation = 'left'; // if groups are present if (groupIds.length > 0) { for (var i = 0; i < groupIds.length; i++) { orientation = 'left'; var group = this.groups[groupIds[i]]; if (group.visible == true) { if (group.options.yAxisOrientation == 'right') { orientation = 'right'; } minVal = groupRanges[i].min; maxVal = groupRanges[i].max; if (orientation == 'left') { yAxisLeftUsed = true; minLeft = minLeft > minVal ? minVal : minLeft; maxLeft = maxLeft < maxVal ? maxVal : maxLeft; } else { yAxisRightUsed = true; minRight = minRight > minVal ? minVal : minRight; maxRight = maxRight < maxVal ? maxVal : maxRight; } } } if (yAxisLeftUsed == true) { this.yAxisLeft.setRange(minLeft, maxLeft); } if (yAxisRightUsed == true) { this.yAxisRight.setRange(minRight, maxRight); } } changeCalled = this._toggleAxisVisiblity(yAxisLeftUsed , this.yAxisLeft) || changeCalled; changeCalled = this._toggleAxisVisiblity(yAxisRightUsed, this.yAxisRight) || changeCalled; if (yAxisRightUsed == true && yAxisLeftUsed == true) { this.yAxisLeft.drawIcons = true; this.yAxisRight.drawIcons = true; } else { this.yAxisLeft.drawIcons = false; this.yAxisRight.drawIcons = false; } this.yAxisRight.master = !yAxisLeftUsed; if (this.yAxisRight.master == false) { if (yAxisRightUsed == true) {this.yAxisLeft.lineOffset = this.yAxisRight.width;} else {this.yAxisLeft.lineOffset = 0;} changeCalled = this.yAxisLeft.redraw() || changeCalled; this.yAxisRight.stepPixelsForced = this.yAxisLeft.stepPixels; changeCalled = this.yAxisRight.redraw() || changeCalled; } else { changeCalled = this.yAxisRight.redraw() || changeCalled; } return changeCalled; }; /** * This shows or hides the Y axis if needed. If there is a change, the changed event is emitted by the updateYAxis function * * @param {boolean} axisUsed * @returns {boolean} * @private * @param axis */ LineGraph.prototype._toggleAxisVisiblity = function (axisUsed, axis) { var changed = false; if (axisUsed == false) { if (axis.dom.frame.parentNode) { axis.hide(); changed = true; } } else { if (!axis.dom.frame.parentNode) { axis.show(); changed = true; } } return changed; }; /** * draw a bar graph * @param datapoints * @param group */ LineGraph.prototype._drawBarGraph = function (dataset, group) { if (dataset != null) { if (dataset.length > 0) { var coreDistance; var minWidth = 0.1 * group.options.barChart.width; var offset = 0; var width = group.options.barChart.width; if (group.options.barChart.align == 'left') {offset -= 0.5*width;} else if (group.options.barChart.align == 'right') {offset += 0.5*width;} for (var i = 0; i < dataset.length; i++) { // dynammically downscale the width so there is no overlap up to 1/10th the original width if (i+1 < dataset.length) {coreDistance = Math.abs(dataset[i+1].x - dataset[i].x);} if (i > 0) {coreDistance = Math.min(coreDistance,Math.abs(dataset[i-1].x - dataset[i].x));} if (coreDistance < width) {width = coreDistance < minWidth ? minWidth : coreDistance;} DOMutil.drawBar(dataset[i].x + offset, dataset[i].y, width, group.zeroPosition - dataset[i].y, group.className + ' bar', this.svgElements, this.svg); } // draw points if (group.options.drawPoints.enabled == true) { this._drawPoints(dataset, group, this.svgElements, this.svg, offset); } } } }; /** * draw a line graph * * @param datapoints * @param group */ LineGraph.prototype._drawLineGraph = function (dataset, group) { if (dataset != null) { if (dataset.length > 0) { var path, d; var svgHeight = Number(this.svg.style.height.replace("px","")); path = DOMutil.getSVGElement('path', this.svgElements, this.svg); path.setAttributeNS(null, "class", group.className); // construct path from dataset if (group.options.catmullRom.enabled == true) { d = this._catmullRom(dataset, group); } else { d = this._linear(dataset); } // append with points for fill and finalize the path if (group.options.shaded.enabled == true) { var fillPath = DOMutil.getSVGElement('path',this.svgElements, this.svg); var dFill; if (group.options.shaded.orientation == 'top') { dFill = "M" + dataset[0].x + "," + 0 + " " + d + "L" + dataset[dataset.length - 1].x + "," + 0; } else { dFill = "M" + dataset[0].x + "," + svgHeight + " " + d + "L" + dataset[dataset.length - 1].x + "," + svgHeight; } fillPath.setAttributeNS(null, "class", group.className + " fill"); fillPath.setAttributeNS(null, "d", dFill); } // copy properties to path for drawing. path.setAttributeNS(null, "d", "M" + d); // draw points if (group.options.drawPoints.enabled == true) { this._drawPoints(dataset, group, this.svgElements, this.svg); } } } }; /** * draw the data points * * @param dataset * @param JSONcontainer * @param svg * @param group */ LineGraph.prototype._drawPoints = function (dataset, group, JSONcontainer, svg, offset) { if (offset === undefined) {offset = 0;} for (var i = 0; i < dataset.length; i++) { DOMutil.drawPoint(dataset[i].x + offset, dataset[i].y, group, JSONcontainer, svg); } }; /** * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for * the yAxis. * * @param datapoints * @returns {Array} * @private */ LineGraph.prototype._preprocessData = function (datapoints, group) { var extractedData = []; var xValue, yValue; var toScreen = this.body.util.toScreen; var increment = 1; var amountOfPoints = datapoints.length; var yMin = datapoints[0].y; var yMax = datapoints[0].y; // the global screen is used because changing the width of the yAxis may affect the increment, resulting in an endless loop // of width changing of the yAxis. if (group.options.sampling == true) { var xDistance = this.body.util.toGlobalScreen(datapoints[datapoints.length-1].x) - this.body.util.toGlobalScreen(datapoints[0].x); var pointsPerPixel = amountOfPoints/xDistance; increment = Math.min(Math.ceil(0.2 * amountOfPoints), Math.max(1,Math.round(pointsPerPixel))); } for (var i = 0; i < amountOfPoints; i += increment) { xValue = toScreen(datapoints[i].x) + this.width - 1; yValue = datapoints[i].y; extractedData.push({x: xValue, y: yValue}); yMin = yMin > yValue ? yValue : yMin; yMax = yMax < yValue ? yValue : yMax; } // extractedData.sort(function (a,b) {return a.x - b.x;}); return {min: yMin, max: yMax, data: extractedData}; }; /** * This uses the DataAxis object to generate the correct Y coordinate on the SVG window. It uses the * util function toScreen to get the x coordinate from the timestamp. * * @param datapoints * @param options * @returns {Array} * @private */ LineGraph.prototype._convertYvalues = function (datapoints, group) { var extractedData = []; var xValue, yValue; var axis = this.yAxisLeft; var svgHeight = Number(this.svg.style.height.replace("px","")); if (group.options.yAxisOrientation == 'right') { axis = this.yAxisRight; } for (var i = 0; i < datapoints.length; i++) { xValue = datapoints[i].x; yValue = Math.round(axis.convertValue(datapoints[i].y)); extractedData.push({x: xValue, y: yValue}); } group.setZeroPosition(Math.min(svgHeight, axis.convertValue(0))); // extractedData.sort(function (a,b) {return a.x - b.x;}); return extractedData; }; /** * This uses an uniform parametrization of the CatmullRom algorithm: * "On the Parameterization of Catmull-Rom Curves" by Cem Yuksel et al. * @param data * @returns {string} * @private */ LineGraph.prototype._catmullRomUniform = function(data) { // catmull rom var p0, p1, p2, p3, bp1, bp2; var d = Math.round(data[0].x) + "," + Math.round(data[0].y) + " "; var normalization = 1/6; var length = data.length; for (var i = 0; i < length - 1; i++) { p0 = (i == 0) ? data[0] : data[i-1]; p1 = data[i]; p2 = data[i+1]; p3 = (i + 2 < length) ? data[i+2] : p2; // Catmull-Rom to Cubic Bezier conversion matrix // 0 1 0 0 // -1/6 1 1/6 0 // 0 1/6 1 -1/6 // 0 0 1 0 // bp0 = { x: p1.x, y: p1.y }; bp1 = { x: ((-p0.x + 6*p1.x + p2.x) *normalization), y: ((-p0.y + 6*p1.y + p2.y) *normalization)}; bp2 = { x: (( p1.x + 6*p2.x - p3.x) *normalization), y: (( p1.y + 6*p2.y - p3.y) *normalization)}; // bp0 = { x: p2.x, y: p2.y }; d += "C" + bp1.x + "," + bp1.y + " " + bp2.x + "," + bp2.y + " " + p2.x + "," + p2.y + " "; } return d; }; /** * This uses either the chordal or centripetal parameterization of the catmull-rom algorithm. * By default, the centripetal parameterization is used because this gives the nicest results. * These parameterizations are relatively heavy because the distance between 4 points have to be calculated. * * One optimization can be used to reuse distances since this is a sliding window approach. * @param data * @returns {string} * @private */ LineGraph.prototype._catmullRom = function(data, group) { var alpha = group.options.catmullRom.alpha; if (alpha == 0 || alpha === undefined) { return this._catmullRomUniform(data); } else { var p0, p1, p2, p3, bp1, bp2, d1,d2,d3, A, B, N, M; var d3powA, d2powA, d3pow2A, d2pow2A, d1pow2A, d1powA; var d = Math.round(data[0].x) + "," + Math.round(data[0].y) + " "; var length = data.length; for (var i = 0; i < length - 1; i++) { p0 = (i == 0) ? data[0] : data[i-1]; p1 = data[i]; p2 = data[i+1]; p3 = (i + 2 < length) ? data[i+2] : p2; d1 = Math.sqrt(Math.pow(p0.x - p1.x,2) + Math.pow(p0.y - p1.y,2)); d2 = Math.sqrt(Math.pow(p1.x - p2.x,2) + Math.pow(p1.y - p2.y,2)); d3 = Math.sqrt(Math.pow(p2.x - p3.x,2) + Math.pow(p2.y - p3.y,2)); // Catmull-Rom to Cubic Bezier conversion matrix // // A = 2d1^2a + 3d1^a * d2^a + d3^2a // B = 2d3^2a + 3d3^a * d2^a + d2^2a // // [ 0 1 0 0 ] // [ -d2^2a/N A/N d1^2a/N 0 ] // [ 0 d3^2a/M B/M -d2^2a/M ] // [ 0 0 1 0 ] // [ 0 1 0 0 ] // [ -d2pow2a/N A/N d1pow2a/N 0 ] // [ 0 d3pow2a/M B/M -d2pow2a/M ] // [ 0 0 1 0 ] d3powA = Math.pow(d3, alpha); d3pow2A = Math.pow(d3,2*alpha); d2powA = Math.pow(d2, alpha); d2pow2A = Math.pow(d2,2*alpha); d1powA = Math.pow(d1, alpha); d1pow2A = Math.pow(d1,2*alpha); A = 2*d1pow2A + 3*d1powA * d2powA + d2pow2A; B = 2*d3pow2A + 3*d3powA * d2powA + d2pow2A; N = 3*d1powA * (d1powA + d2powA); if (N > 0) {N = 1 / N;} M = 3*d3powA * (d3powA + d2powA); if (M > 0) {M = 1 / M;} bp1 = { x: ((-d2pow2A * p0.x + A*p1.x + d1pow2A * p2.x) * N), y: ((-d2pow2A * p0.y + A*p1.y + d1pow2A * p2.y) * N)}; bp2 = { x: (( d3pow2A * p1.x + B*p2.x - d2pow2A * p3.x) * M), y: (( d3pow2A * p1.y + B*p2.y - d2pow2A * p3.y) * M)}; if (bp1.x == 0 && bp1.y == 0) {bp1 = p1;} if (bp2.x == 0 && bp2.y == 0) {bp2 = p2;} d += "C" + bp1.x + "," + bp1.y + " " + bp2.x + "," + bp2.y + " " + p2.x + "," + p2.y + " "; } return d; } }; /** * this generates the SVG path for a linear drawing between datapoints. * @param data * @returns {string} * @private */ LineGraph.prototype._linear = function(data) { // linear var d = ""; for (var i = 0; i < data.length; i++) { if (i == 0) { d += data[i].x + "," + data[i].y; } else { d += " " + data[i].x + "," + data[i].y; } } return d; }; module.exports = LineGraph; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var Component = __webpack_require__(18); var TimeStep = __webpack_require__(17); /** * A horizontal time axis * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} body * @param {Object} [options] See TimeAxis.setOptions for the available * options. * @constructor TimeAxis * @extends Component */ function TimeAxis (body, options) { this.dom = { foreground: null, majorLines: [], majorTexts: [], minorLines: [], minorTexts: [], redundant: { majorLines: [], majorTexts: [], minorLines: [], minorTexts: [] } }; this.props = { range: { start: 0, end: 0, minimumStep: 0 }, lineTop: 0 }; this.defaultOptions = { orientation: 'bottom', // supported: 'top', 'bottom' // TODO: implement timeaxis orientations 'left' and 'right' showMinorLabels: true, showMajorLabels: true }; this.options = util.extend({}, this.defaultOptions); this.body = body; // create the HTML DOM this._create(); this.setOptions(options); } TimeAxis.prototype = new Component(); /** * Set options for the TimeAxis. * Parameters will be merged in current options. * @param {Object} options Available options: * {string} [orientation] * {boolean} [showMinorLabels] * {boolean} [showMajorLabels] */ TimeAxis.prototype.setOptions = function(options) { if (options) { // copy all options that we know util.selectiveExtend(['orientation', 'showMinorLabels', 'showMajorLabels'], this.options, options); } }; /** * Create the HTML DOM for the TimeAxis */ TimeAxis.prototype._create = function() { this.dom.foreground = document.createElement('div'); this.dom.background = document.createElement('div'); this.dom.foreground.className = 'timeaxis foreground'; this.dom.background.className = 'timeaxis background'; }; /** * Destroy the TimeAxis */ TimeAxis.prototype.destroy = function() { // remove from DOM if (this.dom.foreground.parentNode) { this.dom.foreground.parentNode.removeChild(this.dom.foreground); } if (this.dom.background.parentNode) { this.dom.background.parentNode.removeChild(this.dom.background); } this.body = null; }; /** * Repaint the component * @return {boolean} Returns true if the component is resized */ TimeAxis.prototype.redraw = function () { var options = this.options, props = this.props, foreground = this.dom.foreground, background = this.dom.background; // determine the correct parent DOM element (depending on option orientation) var parent = (options.orientation == 'top') ? this.body.dom.top : this.body.dom.bottom; var parentChanged = (foreground.parentNode !== parent); // calculate character width and height this._calculateCharSize(); // TODO: recalculate sizes only needed when parent is resized or options is changed var orientation = this.options.orientation, showMinorLabels = this.options.showMinorLabels, showMajorLabels = this.options.showMajorLabels; // determine the width and height of the elemens for the axis props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0; props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0; props.height = props.minorLabelHeight + props.majorLabelHeight; props.width = foreground.offsetWidth; props.minorLineHeight = this.body.domProps.root.height - props.majorLabelHeight - (options.orientation == 'top' ? this.body.domProps.bottom.height : this.body.domProps.top.height); props.minorLineWidth = 1; // TODO: really calculate width props.majorLineHeight = props.minorLineHeight + props.majorLabelHeight; props.majorLineWidth = 1; // TODO: really calculate width // take foreground and background offline while updating (is almost twice as fast) var foregroundNextSibling = foreground.nextSibling; var backgroundNextSibling = background.nextSibling; foreground.parentNode && foreground.parentNode.removeChild(foreground); background.parentNode && background.parentNode.removeChild(background); foreground.style.height = this.props.height + 'px'; this._repaintLabels(); // put DOM online again (at the same place) if (foregroundNextSibling) { parent.insertBefore(foreground, foregroundNextSibling); } else { parent.appendChild(foreground) } if (backgroundNextSibling) { this.body.dom.backgroundVertical.insertBefore(background, backgroundNextSibling); } else { this.body.dom.backgroundVertical.appendChild(background) } return this._isResized() || parentChanged; }; /** * Repaint major and minor text labels and vertical grid lines * @private */ TimeAxis.prototype._repaintLabels = function () { var orientation = this.options.orientation; // calculate range and step (step such that we have space for 7 characters per label) var start = util.convert(this.body.range.start, 'Number'), end = util.convert(this.body.range.end, 'Number'), minimumStep = this.body.util.toTime((this.props.minorCharWidth || 10) * 7).valueOf() -this.body.util.toTime(0).valueOf(); var step = new TimeStep(new Date(start), new Date(end), minimumStep); this.step = step; // Move all DOM elements to a "redundant" list, where they // can be picked for re-use, and clear the lists with lines and texts. // At the end of the function _repaintLabels, left over elements will be cleaned up var dom = this.dom; dom.redundant.majorLines = dom.majorLines; dom.redundant.majorTexts = dom.majorTexts; dom.redundant.minorLines = dom.minorLines; dom.redundant.minorTexts = dom.minorTexts; dom.majorLines = []; dom.majorTexts = []; dom.minorLines = []; dom.minorTexts = []; step.first(); var xFirstMajorLabel = undefined; var max = 0; while (step.hasNext() && max < 1000) { max++; var cur = step.getCurrent(), x = this.body.util.toScreen(cur), isMajor = step.isMajor(); // TODO: lines must have a width, such that we can create css backgrounds if (this.options.showMinorLabels) { this._repaintMinorText(x, step.getLabelMinor(), orientation); } if (isMajor && this.options.showMajorLabels) { if (x > 0) { if (xFirstMajorLabel == undefined) { xFirstMajorLabel = x; } this._repaintMajorText(x, step.getLabelMajor(), orientation); } this._repaintMajorLine(x, orientation); } else { this._repaintMinorLine(x, orientation); } step.next(); } // create a major label on the left when needed if (this.options.showMajorLabels) { var leftTime = this.body.util.toTime(0), leftText = step.getLabelMajor(leftTime), widthText = leftText.length * (this.props.majorCharWidth || 10) + 10; // upper bound estimation if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) { this._repaintMajorText(0, leftText, orientation); } } // Cleanup leftover DOM elements from the redundant list util.forEach(this.dom.redundant, function (arr) { while (arr.length) { var elem = arr.pop(); if (elem && elem.parentNode) { elem.parentNode.removeChild(elem); } } }); }; /** * Create a minor label for the axis at position x * @param {Number} x * @param {String} text * @param {String} orientation "top" or "bottom" (default) * @private */ TimeAxis.prototype._repaintMinorText = function (x, text, orientation) { // reuse redundant label var label = this.dom.redundant.minorTexts.shift(); if (!label) { // create new label var content = document.createTextNode(''); label = document.createElement('div'); label.appendChild(content); label.className = 'text minor'; this.dom.foreground.appendChild(label); } this.dom.minorTexts.push(label); label.childNodes[0].nodeValue = text; label.style.top = (orientation == 'top') ? (this.props.majorLabelHeight + 'px') : '0'; label.style.left = x + 'px'; //label.title = title; // TODO: this is a heavy operation }; /** * Create a Major label for the axis at position x * @param {Number} x * @param {String} text * @param {String} orientation "top" or "bottom" (default) * @private */ TimeAxis.prototype._repaintMajorText = function (x, text, orientation) { // reuse redundant label var label = this.dom.redundant.majorTexts.shift(); if (!label) { // create label var content = document.createTextNode(text); label = document.createElement('div'); label.className = 'text major'; label.appendChild(content); this.dom.foreground.appendChild(label); } this.dom.majorTexts.push(label); label.childNodes[0].nodeValue = text; //label.title = title; // TODO: this is a heavy operation label.style.top = (orientation == 'top') ? '0' : (this.props.minorLabelHeight + 'px'); label.style.left = x + 'px'; }; /** * Create a minor line for the axis at position x * @param {Number} x * @param {String} orientation "top" or "bottom" (default) * @private */ TimeAxis.prototype._repaintMinorLine = function (x, orientation) { // reuse redundant line var line = this.dom.redundant.minorLines.shift(); if (!line) { // create vertical line line = document.createElement('div'); line.className = 'grid vertical minor'; this.dom.background.appendChild(line); } this.dom.minorLines.push(line); var props = this.props; if (orientation == 'top') { line.style.top = props.majorLabelHeight + 'px'; } else { line.style.top = this.body.domProps.top.height + 'px'; } line.style.height = props.minorLineHeight + 'px'; line.style.left = (x - props.minorLineWidth / 2) + 'px'; }; /** * Create a Major line for the axis at position x * @param {Number} x * @param {String} orientation "top" or "bottom" (default) * @private */ TimeAxis.prototype._repaintMajorLine = function (x, orientation) { // reuse redundant line var line = this.dom.redundant.majorLines.shift(); if (!line) { // create vertical line line = document.createElement('DIV'); line.className = 'grid vertical major'; this.dom.background.appendChild(line); } this.dom.majorLines.push(line); var props = this.props; if (orientation == 'top') { line.style.top = '0'; } else { line.style.top = this.body.domProps.top.height + 'px'; } line.style.left = (x - props.majorLineWidth / 2) + 'px'; line.style.height = props.majorLineHeight + 'px'; }; /** * Determine the size of text on the axis (both major and minor axis). * The size is calculated only once and then cached in this.props. * @private */ TimeAxis.prototype._calculateCharSize = function () { // Note: We calculate char size with every redraw. Size may change, for // example when any of the timelines parents had display:none for example. // determine the char width and height on the minor axis if (!this.dom.measureCharMinor) { this.dom.measureCharMinor = document.createElement('DIV'); this.dom.measureCharMinor.className = 'text minor measure'; this.dom.measureCharMinor.style.position = 'absolute'; this.dom.measureCharMinor.appendChild(document.createTextNode('0')); this.dom.foreground.appendChild(this.dom.measureCharMinor); } this.props.minorCharHeight = this.dom.measureCharMinor.clientHeight; this.props.minorCharWidth = this.dom.measureCharMinor.clientWidth; // determine the char width and height on the major axis if (!this.dom.measureCharMajor) { this.dom.measureCharMajor = document.createElement('DIV'); this.dom.measureCharMajor.className = 'text minor measure'; this.dom.measureCharMajor.style.position = 'absolute'; this.dom.measureCharMajor.appendChild(document.createTextNode('0')); this.dom.foreground.appendChild(this.dom.measureCharMajor); } this.props.majorCharHeight = this.dom.measureCharMajor.clientHeight; this.props.majorCharWidth = this.dom.measureCharMajor.clientWidth; }; /** * Snap a date to a rounded value. * The snap intervals are dependent on the current scale and step. * @param {Date} date the date to be snapped. * @return {Date} snappedDate */ TimeAxis.prototype.snap = function(date) { return this.step.snap(date); }; module.exports = TimeAxis; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { var Item = __webpack_require__(29); /** * @constructor ItemBox * @extends Item * @param {Object} data Object containing parameters start * content, className. * @param {{toScreen: function, toTime: function}} conversion * Conversion functions from time to screen and vice versa * @param {Object} [options] Configuration options * // TODO: describe available options */ function ItemBox (data, conversion, options) { this.props = { dot: { width: 0, height: 0 }, line: { width: 0, height: 0 } }; // validate data if (data) { if (data.start == undefined) { throw new Error('Property "start" missing in item ' + data); } } Item.call(this, data, conversion, options); } ItemBox.prototype = new Item (null, null, null); /** * Check whether this item is visible inside given range * @returns {{start: Number, end: Number}} range with a timestamp for start and end * @returns {boolean} True if visible */ ItemBox.prototype.isVisible = function(range) { // determine visibility // TODO: account for the real width of the item. Right now we just add 1/4 to the window var interval = (range.end - range.start) / 4; return (this.data.start > range.start - interval) && (this.data.start < range.end + interval); }; /** * Repaint the item */ ItemBox.prototype.redraw = function() { var dom = this.dom; if (!dom) { // create DOM this.dom = {}; dom = this.dom; // create main box dom.box = document.createElement('DIV'); // contents box (inside the background box). used for making margins dom.content = document.createElement('DIV'); dom.content.className = 'content'; dom.box.appendChild(dom.content); // line to axis dom.line = document.createElement('DIV'); dom.line.className = 'line'; // dot on axis dom.dot = document.createElement('DIV'); dom.dot.className = 'dot'; // attach this item as attribute dom.box['timeline-item'] = this; } // append DOM to parent DOM if (!this.parent) { throw new Error('Cannot redraw item: no parent attached'); } if (!dom.box.parentNode) { var foreground = this.parent.dom.foreground; if (!foreground) throw new Error('Cannot redraw time axis: parent has no foreground container element'); foreground.appendChild(dom.box); } if (!dom.line.parentNode) { var background = this.parent.dom.background; if (!background) throw new Error('Cannot redraw time axis: parent has no background container element'); background.appendChild(dom.line); } if (!dom.dot.parentNode) { var axis = this.parent.dom.axis; if (!background) throw new Error('Cannot redraw time axis: parent has no axis container element'); axis.appendChild(dom.dot); } this.displayed = true; // update contents if (this.data.content != this.content) { this.content = this.data.content; if (this.content instanceof Element) { dom.content.innerHTML = ''; dom.content.appendChild(this.content); } else if (this.data.content != undefined) { dom.content.innerHTML = this.content; } else { throw new Error('Property "content" missing in item ' + this.data.id); } this.dirty = true; } // update title if (this.data.title != this.title) { dom.box.title = this.data.title; this.title = this.data.title; } // update class var className = (this.data.className? ' ' + this.data.className : '') + (this.selected ? ' selected' : ''); if (this.className != className) { this.className = className; dom.box.className = 'item box' + className; dom.line.className = 'item line' + className; dom.dot.className = 'item dot' + className; this.dirty = true; } // recalculate size if (this.dirty) { this.props.dot.height = dom.dot.offsetHeight; this.props.dot.width = dom.dot.offsetWidth; this.props.line.width = dom.line.offsetWidth; this.width = dom.box.offsetWidth; this.height = dom.box.offsetHeight; this.dirty = false; } this._repaintDeleteButton(dom.box); }; /** * Show the item in the DOM (when not already displayed). The items DOM will * be created when needed. */ ItemBox.prototype.show = function() { if (!this.displayed) { this.redraw(); } }; /** * Hide the item from the DOM (when visible) */ ItemBox.prototype.hide = function() { if (this.displayed) { var dom = this.dom; if (dom.box.parentNode) dom.box.parentNode.removeChild(dom.box); if (dom.line.parentNode) dom.line.parentNode.removeChild(dom.line); if (dom.dot.parentNode) dom.dot.parentNode.removeChild(dom.dot); this.top = null; this.left = null; this.displayed = false; } }; /** * Reposition the item horizontally * @Override */ ItemBox.prototype.repositionX = function() { var start = this.conversion.toScreen(this.data.start), align = this.options.align, left, box = this.dom.box, line = this.dom.line, dot = this.dom.dot; // calculate left position of the box if (align == 'right') { this.left = start - this.width; } else if (align == 'left') { this.left = start; } else { // default or 'center' this.left = start - this.width / 2; } // reposition box box.style.left = this.left + 'px'; // reposition line line.style.left = (start - this.props.line.width / 2) + 'px'; // reposition dot dot.style.left = (start - this.props.dot.width / 2) + 'px'; }; /** * Reposition the item vertically * @Override */ ItemBox.prototype.repositionY = function() { var orientation = this.options.orientation, box = this.dom.box, line = this.dom.line, dot = this.dom.dot; if (orientation == 'top') { box.style.top = (this.top || 0) + 'px'; line.style.top = '0'; line.style.height = (this.parent.top + this.top + 1) + 'px'; line.style.bottom = ''; } else { // orientation 'bottom' var itemSetHeight = this.parent.itemSet.props.height; // TODO: this is nasty var lineHeight = itemSetHeight - this.parent.top - this.parent.height + this.top; box.style.top = (this.parent.height - this.top - this.height || 0) + 'px'; line.style.top = (itemSetHeight - lineHeight) + 'px'; line.style.bottom = '0'; } dot.style.top = (-this.props.dot.height / 2) + 'px'; }; module.exports = ItemBox; /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { var Hammer = __webpack_require__(41); /** * @constructor Item * @param {Object} data Object containing (optional) parameters type, * start, end, content, group, className. * @param {{toScreen: function, toTime: function}} conversion * Conversion functions from time to screen and vice versa * @param {Object} options Configuration options * // TODO: describe available options */ function Item (data, conversion, options) { this.id = null; this.parent = null; this.data = data; this.dom = null; this.conversion = conversion || {}; this.options = options || {}; this.selected = false; this.displayed = false; this.dirty = true; this.top = null; this.left = null; this.width = null; this.height = null; } /** * Select current item */ Item.prototype.select = function() { this.selected = true; if (this.displayed) this.redraw(); }; /** * Unselect current item */ Item.prototype.unselect = function() { this.selected = false; if (this.displayed) this.redraw(); }; /** * Set a parent for the item * @param {ItemSet | Group} parent */ Item.prototype.setParent = function(parent) { if (this.displayed) { this.hide(); this.parent = parent; if (this.parent) { this.show(); } } else { this.parent = parent; } }; /** * Check whether this item is visible inside given range * @returns {{start: Number, end: Number}} range with a timestamp for start and end * @returns {boolean} True if visible */ Item.prototype.isVisible = function(range) { // Should be implemented by Item implementations return false; }; /** * Show the Item in the DOM (when not already visible) * @return {Boolean} changed */ Item.prototype.show = function() { return false; }; /** * Hide the Item from the DOM (when visible) * @return {Boolean} changed */ Item.prototype.hide = function() { return false; }; /** * Repaint the item */ Item.prototype.redraw = function() { // should be implemented by the item }; /** * Reposition the Item horizontally */ Item.prototype.repositionX = function() { // should be implemented by the item }; /** * Reposition the Item vertically */ Item.prototype.repositionY = function() { // should be implemented by the item }; /** * Repaint a delete button on the top right of the item when the item is selected * @param {HTMLElement} anchor * @protected */ Item.prototype._repaintDeleteButton = function (anchor) { if (this.selected && this.options.editable.remove && !this.dom.deleteButton) { // create and show button var me = this; var deleteButton = document.createElement('div'); deleteButton.className = 'delete'; deleteButton.title = 'Delete this item'; Hammer(deleteButton, { preventDefault: true }).on('tap', function (event) { me.parent.removeFromDataSet(me); event.stopPropagation(); }); anchor.appendChild(deleteButton); this.dom.deleteButton = deleteButton; } else if (!this.selected && this.dom.deleteButton) { // remove button if (this.dom.deleteButton.parentNode) { this.dom.deleteButton.parentNode.removeChild(this.dom.deleteButton); } this.dom.deleteButton = null; } }; module.exports = Item; /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { var Item = __webpack_require__(29); /** * @constructor ItemPoint * @extends Item * @param {Object} data Object containing parameters start * content, className. * @param {{toScreen: function, toTime: function}} conversion * Conversion functions from time to screen and vice versa * @param {Object} [options] Configuration options * // TODO: describe available options */ function ItemPoint (data, conversion, options) { this.props = { dot: { top: 0, width: 0, height: 0 }, content: { height: 0, marginLeft: 0 } }; // validate data if (data) { if (data.start == undefined) { throw new Error('Property "start" missing in item ' + data); } } Item.call(this, data, conversion, options); } ItemPoint.prototype = new Item (null, null, null); /** * Check whether this item is visible inside given range * @returns {{start: Number, end: Number}} range with a timestamp for start and end * @returns {boolean} True if visible */ ItemPoint.prototype.isVisible = function(range) { // determine visibility // TODO: account for the real width of the item. Right now we just add 1/4 to the window var interval = (range.end - range.start) / 4; return (this.data.start > range.start - interval) && (this.data.start < range.end + interval); }; /** * Repaint the item */ ItemPoint.prototype.redraw = function() { var dom = this.dom; if (!dom) { // create DOM this.dom = {}; dom = this.dom; // background box dom.point = document.createElement('div'); // className is updated in redraw() // contents box, right from the dot dom.content = document.createElement('div'); dom.content.className = 'content'; dom.point.appendChild(dom.content); // dot at start dom.dot = document.createElement('div'); dom.point.appendChild(dom.dot); // attach this item as attribute dom.point['timeline-item'] = this; } // append DOM to parent DOM if (!this.parent) { throw new Error('Cannot redraw item: no parent attached'); } if (!dom.point.parentNode) { var foreground = this.parent.dom.foreground; if (!foreground) { throw new Error('Cannot redraw time axis: parent has no foreground container element'); } foreground.appendChild(dom.point); } this.displayed = true; // update contents if (this.data.content != this.content) { this.content = this.data.content; if (this.content instanceof Element) { dom.content.innerHTML = ''; dom.content.appendChild(this.content); } else if (this.data.content != undefined) { dom.content.innerHTML = this.content; } else { throw new Error('Property "content" missing in item ' + this.data.id); } this.dirty = true; } // update title if (this.data.title != this.title) { dom.point.title = this.data.title; this.title = this.data.title; } // update class var className = (this.data.className? ' ' + this.data.className : '') + (this.selected ? ' selected' : ''); if (this.className != className) { this.className = className; dom.point.className = 'item point' + className; dom.dot.className = 'item dot' + className; this.dirty = true; } // recalculate size if (this.dirty) { this.width = dom.point.offsetWidth; this.height = dom.point.offsetHeight; this.props.dot.width = dom.dot.offsetWidth; this.props.dot.height = dom.dot.offsetHeight; this.props.content.height = dom.content.offsetHeight; // resize contents dom.content.style.marginLeft = 2 * this.props.dot.width + 'px'; //dom.content.style.marginRight = ... + 'px'; // TODO: margin right dom.dot.style.top = ((this.height - this.props.dot.height) / 2) + 'px'; dom.dot.style.left = (this.props.dot.width / 2) + 'px'; this.dirty = false; } this._repaintDeleteButton(dom.point); }; /** * Show the item in the DOM (when not already visible). The items DOM will * be created when needed. */ ItemPoint.prototype.show = function() { if (!this.displayed) { this.redraw(); } }; /** * Hide the item from the DOM (when visible) */ ItemPoint.prototype.hide = function() { if (this.displayed) { if (this.dom.point.parentNode) { this.dom.point.parentNode.removeChild(this.dom.point); } this.top = null; this.left = null; this.displayed = false; } }; /** * Reposition the item horizontally * @Override */ ItemPoint.prototype.repositionX = function() { var start = this.conversion.toScreen(this.data.start); this.left = start - this.props.dot.width; // reposition point this.dom.point.style.left = this.left + 'px'; }; /** * Reposition the item vertically * @Override */ ItemPoint.prototype.repositionY = function() { var orientation = this.options.orientation, point = this.dom.point; if (orientation == 'top') { point.style.top = this.top + 'px'; } else { point.style.top = (this.parent.height - this.top - this.height) + 'px'; } }; module.exports = ItemPoint; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { var Hammer = __webpack_require__(41); var Item = __webpack_require__(29); /** * @constructor ItemRange * @extends Item * @param {Object} data Object containing parameters start, end * content, className. * @param {{toScreen: function, toTime: function}} conversion * Conversion functions from time to screen and vice versa * @param {Object} [options] Configuration options * // TODO: describe options */ function ItemRange (data, conversion, options) { this.props = { content: { width: 0 } }; this.overflow = false; // if contents can overflow (css styling), this flag is set to true // validate data if (data) { if (data.start == undefined) { throw new Error('Property "start" missing in item ' + data.id); } if (data.end == undefined) { throw new Error('Property "end" missing in item ' + data.id); } } Item.call(this, data, conversion, options); } ItemRange.prototype = new Item (null, null, null); ItemRange.prototype.baseClassName = 'item range'; /** * Check whether this item is visible inside given range * @returns {{start: Number, end: Number}} range with a timestamp for start and end * @returns {boolean} True if visible */ ItemRange.prototype.isVisible = function(range) { // determine visibility return (this.data.start < range.end) && (this.data.end > range.start); }; /** * Repaint the item */ ItemRange.prototype.redraw = function() { var dom = this.dom; if (!dom) { // create DOM this.dom = {}; dom = this.dom; // background box dom.box = document.createElement('div'); // className is updated in redraw() // contents box dom.content = document.createElement('div'); dom.content.className = 'content'; dom.box.appendChild(dom.content); // attach this item as attribute dom.box['timeline-item'] = this; } // append DOM to parent DOM if (!this.parent) { throw new Error('Cannot redraw item: no parent attached'); } if (!dom.box.parentNode) { var foreground = this.parent.dom.foreground; if (!foreground) { throw new Error('Cannot redraw time axis: parent has no foreground container element'); } foreground.appendChild(dom.box); } this.displayed = true; // update contents if (this.data.content != this.content) { this.content = this.data.content; if (this.content instanceof Element) { dom.content.innerHTML = ''; dom.content.appendChild(this.content); } else if (this.data.content != undefined) { dom.content.innerHTML = this.content; } else { throw new Error('Property "content" missing in item ' + this.data.id); } this.dirty = true; } // update title if (this.data.title != this.title) { dom.box.title = this.data.title; this.title = this.data.title; } // update class var className = (this.data.className ? (' ' + this.data.className) : '') + (this.selected ? ' selected' : ''); if (this.className != className) { this.className = className; dom.box.className = this.baseClassName + className; this.dirty = true; } // recalculate size if (this.dirty) { // determine from css whether this box has overflow this.overflow = window.getComputedStyle(dom.content).overflow !== 'hidden'; this.props.content.width = this.dom.content.offsetWidth; this.height = this.dom.box.offsetHeight; this.dirty = false; } this._repaintDeleteButton(dom.box); this._repaintDragLeft(); this._repaintDragRight(); }; /** * Show the item in the DOM (when not already visible). The items DOM will * be created when needed. */ ItemRange.prototype.show = function() { if (!this.displayed) { this.redraw(); } }; /** * Hide the item from the DOM (when visible) * @return {Boolean} changed */ ItemRange.prototype.hide = function() { if (this.displayed) { var box = this.dom.box; if (box.parentNode) { box.parentNode.removeChild(box); } this.top = null; this.left = null; this.displayed = false; } }; /** * Reposition the item horizontally * @Override */ // TODO: delete the old function ItemRange.prototype.repositionX = function() { var props = this.props, parentWidth = this.parent.width, start = this.conversion.toScreen(this.data.start), end = this.conversion.toScreen(this.data.end), padding = this.options.padding, contentLeft; // limit the width of the this, as browsers cannot draw very wide divs if (start < -parentWidth) { start = -parentWidth; } if (end > 2 * parentWidth) { end = 2 * parentWidth; } var boxWidth = Math.max(end - start, 1); if (this.overflow) { // when range exceeds left of the window, position the contents at the left of the visible area contentLeft = Math.max(-start, 0); this.left = start; this.width = boxWidth + this.props.content.width; // Note: The calculation of width is an optimistic calculation, giving // a width which will not change when moving the Timeline // So no restacking needed, which is nicer for the eye; } else { // no overflow // when range exceeds left of the window, position the contents at the left of the visible area if (start < 0) { contentLeft = Math.min(-start, (end - start - props.content.width - 2 * padding)); // TODO: remove the need for options.padding. it's terrible. } else { contentLeft = 0; } this.left = start; this.width = boxWidth; } this.dom.box.style.left = this.left + 'px'; this.dom.box.style.width = boxWidth + 'px'; this.dom.content.style.left = contentLeft + 'px'; }; /** * Reposition the item vertically * @Override */ ItemRange.prototype.repositionY = function() { var orientation = this.options.orientation, box = this.dom.box; if (orientation == 'top') { box.style.top = this.top + 'px'; } else { box.style.top = (this.parent.height - this.top - this.height) + 'px'; } }; /** * Repaint a drag area on the left side of the range when the range is selected * @protected */ ItemRange.prototype._repaintDragLeft = function () { if (this.selected && this.options.editable.updateTime && !this.dom.dragLeft) { // create and show drag area var dragLeft = document.createElement('div'); dragLeft.className = 'drag-left'; dragLeft.dragLeftItem = this; // TODO: this should be redundant? Hammer(dragLeft, { preventDefault: true }).on('drag', function () { //console.log('drag left') }); this.dom.box.appendChild(dragLeft); this.dom.dragLeft = dragLeft; } else if (!this.selected && this.dom.dragLeft) { // delete drag area if (this.dom.dragLeft.parentNode) { this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft); } this.dom.dragLeft = null; } }; /** * Repaint a drag area on the right side of the range when the range is selected * @protected */ ItemRange.prototype._repaintDragRight = function () { if (this.selected && this.options.editable.updateTime && !this.dom.dragRight) { // create and show drag area var dragRight = document.createElement('div'); dragRight.className = 'drag-right'; dragRight.dragRightItem = this; // TODO: this should be redundant? Hammer(dragRight, { preventDefault: true }).on('drag', function () { //console.log('drag right') }); this.dom.box.appendChild(dragRight); this.dom.dragRight = dragRight; } else if (!this.selected && this.dom.dragRight) { // delete drag area if (this.dom.dragRight.parentNode) { this.dom.dragRight.parentNode.removeChild(this.dom.dragRight); } this.dom.dragRight = null; } }; module.exports = ItemRange; /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { var Emitter = __webpack_require__(46); var Hammer = __webpack_require__(41); var mousetrap = __webpack_require__(47); var util = __webpack_require__(1); var hammerUtil = __webpack_require__(43); var DataSet = __webpack_require__(3); var DataView = __webpack_require__(4); var dotparser = __webpack_require__(38); var gephiParser = __webpack_require__(39); var Groups = __webpack_require__(34); var Images = __webpack_require__(35); var Node = __webpack_require__(36); var Edge = __webpack_require__(33); var Popup = __webpack_require__(37); var MixinLoader = __webpack_require__(45); // Load custom shapes into CanvasRenderingContext2D __webpack_require__(44); /** * @constructor Network * Create a network visualization, displaying nodes and edges. * * @param {Element} container The DOM element in which the Network will * be created. Normally a div element. * @param {Object} data An object containing parameters * {Array} nodes * {Array} edges * @param {Object} options Options */ function Network (container, data, options) { if (!(this instanceof Network)) { throw new SyntaxError('Constructor must be called with the new operator'); } this._initializeMixinLoaders(); // create variables and set default values this.containerElement = container; // render and calculation settings this.renderRefreshRate = 60; // hz (fps) this.renderTimestep = 1000 / this.renderRefreshRate; // ms -- saves calculation later on this.renderTime = 0.5 * this.renderTimestep; // measured time it takes to render a frame this.maxPhysicsTicksPerRender = 3; // max amount of physics ticks per render step. this.physicsDiscreteStepsize = 0.50; // discrete stepsize of the simulation this.initializing = true; this.triggerFunctions = {add:null,edit:null,editEdge:null,connect:null,del:null}; // set constant values this.defaultOptions = { nodes: { mass: 1, radiusMin: 10, radiusMax: 30, radius: 10, shape: 'ellipse', image: undefined, widthMin: 16, // px widthMax: 64, // px fixed: false, fontColor: 'black', fontSize: 14, // px fontFace: 'verdana', level: -1, color: { border: '#2B7CE9', background: '#97C2FC', highlight: { border: '#2B7CE9', background: '#D2E5FF' }, hover: { border: '#2B7CE9', background: '#D2E5FF' } }, borderColor: '#2B7CE9', backgroundColor: '#97C2FC', highlightColor: '#D2E5FF', group: undefined, borderWidth: 1 }, edges: { widthMin: 1, widthMax: 15, width: 1, widthSelectionMultiplier: 2, hoverWidth: 1.5, style: 'line', color: { color:'#848484', highlight:'#848484', hover: '#848484' }, fontColor: '#343434', fontSize: 14, // px fontFace: 'arial', fontFill: 'white', arrowScaleFactor: 1, dash: { length: 10, gap: 5, altLength: undefined }, inheritColor: "from" // to, from, false, true (== from) }, configurePhysics:false, physics: { barnesHut: { enabled: true, theta: 1 / 0.6, // inverted to save time during calculation gravitationalConstant: -2000, centralGravity: 0.3, springLength: 95, springConstant: 0.04, damping: 0.09 }, repulsion: { centralGravity: 0.0, springLength: 200, springConstant: 0.05, nodeDistance: 100, damping: 0.09 }, hierarchicalRepulsion: { enabled: false, centralGravity: 0.0, springLength: 100, springConstant: 0.01, nodeDistance: 150, damping: 0.09 }, damping: null, centralGravity: null, springLength: null, springConstant: null }, clustering: { // Per Node in Cluster = PNiC enabled: false, // (Boolean) | global on/off switch for clustering. initialMaxNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold. clusterThreshold:500, // (# nodes) | during calculate forces, we check if the total number of nodes is larger than this. If it is, cluster until reduced to reduceToNodes reduceToNodes:300, // (# nodes) | during calculate forces, we check if the total number of nodes is larger than clusterThreshold. If it is, cluster until reduced to this chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains). clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered. sectorThreshold: 100, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector. screenSizeThreshold: 0.2, // (% of canvas) | relative size threshold. If the width or height of a clusternode takes up this much of the screen, decluster node. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px). maxFontSize: 1000, forceAmplification: 0.1, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster). distanceAmplification: 0.1, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster). edgeGrowth: 20, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength. nodeScaling: {width: 1, // (px PNiC) | growth of the width per node in cluster. height: 1, // (px PNiC) | growth of the height per node in cluster. radius: 1}, // (px PNiC) | growth of the radius per node in cluster. maxNodeSizeIncrements: 600, // (# increments) | max growth of the width per node in cluster. activeAreaBoxSize: 80, // (px) | box area around the curser where clusters are popped open. clusterLevelDifference: 2 }, navigation: { enabled: false }, keyboard: { enabled: false, speed: {x: 10, y: 10, zoom: 0.02} }, dataManipulation: { enabled: false, initiallyVisible: false }, hierarchicalLayout: { enabled:false, levelSeparation: 150, nodeSpacing: 100, direction: "UD" // UD, DU, LR, RL }, freezeForStabilization: false, smoothCurves: { enabled: true, dynamic: true, type: "continuous", roundness: 0.5 }, dynamicSmoothCurves: true, maxVelocity: 30, minVelocity: 0.1, // px/s stabilize: true, // stabilize before displaying the network stabilizationIterations: 1000, // maximum number of iteration to stabilize labels:{ add:"Add Node", edit:"Edit", link:"Add Link", del:"Delete selected", editNode:"Edit Node", editEdge:"Edit Edge", back:"Back", addDescription:"Click in an empty space to place a new node.", linkDescription:"Click on a node and drag the edge to another node to connect them.", editEdgeDescription:"Click on the control points and drag them to a node to connect to it.", addError:"The function for add does not support two arguments (data,callback).", linkError:"The function for connect does not support two arguments (data,callback).", editError:"The function for edit does not support two arguments (data, callback).", editBoundError:"No edit function has been bound to this button.", deleteError:"The function for delete does not support two arguments (data, callback).", deleteClusterError:"Clusters cannot be deleted." }, tooltip: { delay: 300, fontColor: 'black', fontSize: 14, // px fontFace: 'verdana', color: { border: '#666', background: '#FFFFC6' } }, dragNetwork: true, dragNodes: true, zoomable: true, hover: false, hideEdgesOnDrag: false, hideNodesOnDrag: false, width : '100%', height : '100%', selectable: true }; this.constants = util.extend({}, this.defaultOptions); this.hoverObj = {nodes:{},edges:{}}; this.controlNodesActive = false; // Node variables var network = this; this.groups = new Groups(); // object with groups this.images = new Images(); // object with images this.images.setOnloadCallback(function () { network._redraw(); }); // keyboard navigation variables this.xIncrement = 0; this.yIncrement = 0; this.zoomIncrement = 0; // loading all the mixins: // load the force calculation functions, grouped under the physics system. this._loadPhysicsSystem(); // create a frame and canvas this._create(); // load the sector system. (mandatory, fully integrated with Network) this._loadSectorSystem(); // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it) this._loadClusterSystem(); // load the selection system. (mandatory, required by Network) this._loadSelectionSystem(); // load the selection system. (mandatory, required by Network) this._loadHierarchySystem(); // apply options this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2); this._setScale(1); this.setOptions(options); // other vars this.freezeSimulation = false;// freeze the simulation this.cachedFunctions = {}; // containers for nodes and edges this.calculationNodes = {}; this.calculationNodeIndices = []; this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation this.nodes = {}; // object with Node objects this.edges = {}; // object with Edge objects // position and scale variables and objects this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw this.pointerPosition = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action this.scale = 1; // defining the global scale variable in the constructor this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out // datasets or dataviews this.nodesData = null; // A DataSet or DataView this.edgesData = null; // A DataSet or DataView // create event listeners used to subscribe on the DataSets of the nodes and edges this.nodesListeners = { 'add': function (event, params) { network._addNodes(params.items); network.start(); }, 'update': function (event, params) { network._updateNodes(params.items); network.start(); }, 'remove': function (event, params) { network._removeNodes(params.items); network.start(); } }; this.edgesListeners = { 'add': function (event, params) { network._addEdges(params.items); network.start(); }, 'update': function (event, params) { network._updateEdges(params.items); network.start(); }, 'remove': function (event, params) { network._removeEdges(params.items); network.start(); } }; // properties for the animation this.moving = true; this.timer = undefined; // Scheduling function. Is definded in this.start(); // load data (the disable start variable will be the same as the enabled clustering) this.setData(data,this.constants.clustering.enabled || this.constants.hierarchicalLayout.enabled); // hierarchical layout this.initializing = false; if (this.constants.hierarchicalLayout.enabled == true) { this._setupHierarchicalLayout(); } else { // zoom so all data will fit on the screen, if clustering is enabled, we do not want start to be called here. if (this.constants.stabilize == false) { this.zoomExtent(true,this.constants.clustering.enabled); } } // if clustering is disabled, the simulation will have started in the setData function if (this.constants.clustering.enabled) { this.startWithClustering(); } } // Extend Network with an Emitter mixin Emitter(Network.prototype); /** * Get the script path where the vis.js library is located * * @returns {string | null} path Path or null when not found. Path does not * end with a slash. * @private */ Network.prototype._getScriptPath = function() { var scripts = document.getElementsByTagName( 'script' ); // find script named vis.js or vis.min.js for (var i = 0; i < scripts.length; i++) { var src = scripts[i].src; var match = src && /\/?vis(.min)?\.js$/.exec(src); if (match) { // return path without the script name return src.substring(0, src.length - match[0].length); } } return null; }; /** * Find the center position of the network * @private */ Network.prototype._getRange = function() { var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node; for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; if (minX > (node.x)) {minX = node.x;} if (maxX < (node.x)) {maxX = node.x;} if (minY > (node.y)) {minY = node.y;} if (maxY < (node.y)) {maxY = node.y;} } } if (minX == 1e9 && maxX == -1e9 && minY == 1e9 && maxY == -1e9) { minY = 0, maxY = 0, minX = 0, maxX = 0; } return {minX: minX, maxX: maxX, minY: minY, maxY: maxY}; }; /** * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY}; * @returns {{x: number, y: number}} * @private */ Network.prototype._findCenter = function(range) { return {x: (0.5 * (range.maxX + range.minX)), y: (0.5 * (range.maxY + range.minY))}; }; /** * center the network * * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY}; */ Network.prototype._centerNetwork = function(range) { var center = this._findCenter(range); center.x *= this.scale; center.y *= this.scale; center.x -= 0.5 * this.frame.canvas.clientWidth; center.y -= 0.5 * this.frame.canvas.clientHeight; this._setTranslation(-center.x,-center.y); // set at 0,0 }; /** * This function zooms out to fit all data on screen based on amount of nodes * * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false; * @param {Boolean} [disableStart] | If true, start is not called. */ Network.prototype.zoomExtent = function(initialZoom, disableStart) { if (initialZoom === undefined) { initialZoom = false; } if (disableStart === undefined) { disableStart = false; } var range = this._getRange(); var zoomLevel; if (initialZoom == true) { var numberOfNodes = this.nodeIndices.length; if (this.constants.smoothCurves == true) { if (this.constants.clustering.enabled == true && numberOfNodes >= this.constants.clustering.initialMaxNodes) { zoomLevel = 49.07548 / (numberOfNodes + 142.05338) + 9.1444e-04; // this is obtained from fitting a dataset from 5 points with scale levels that looked good. } else { zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good. } } else { if (this.constants.clustering.enabled == true && numberOfNodes >= this.constants.clustering.initialMaxNodes) { zoomLevel = 77.5271985 / (numberOfNodes + 187.266146) + 4.76710517e-05; // this is obtained from fitting a dataset from 5 points with scale levels that looked good. } else { zoomLevel = 30.5062972 / (numberOfNodes + 19.93597763) + 0.08413486; // this is obtained from fitting a dataset from 5 points with scale levels that looked good. } } // correct for larger canvasses. var factor = Math.min(this.frame.canvas.clientWidth / 600, this.frame.canvas.clientHeight / 600); zoomLevel *= factor; } else { var xDistance = (Math.abs(range.minX) + Math.abs(range.maxX)) * 1.1; var yDistance = (Math.abs(range.minY) + Math.abs(range.maxY)) * 1.1; var xZoomLevel = this.frame.canvas.clientWidth / xDistance; var yZoomLevel = this.frame.canvas.clientHeight / yDistance; zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel; } if (zoomLevel > 1.0) { zoomLevel = 1.0; } this._setScale(zoomLevel); this._centerNetwork(range); if (disableStart == false) { this.moving = true; this.start(); } }; /** * Update the this.nodeIndices with the most recent node index list * @private */ Network.prototype._updateNodeIndexList = function() { this._clearNodeIndexList(); for (var idx in this.nodes) { if (this.nodes.hasOwnProperty(idx)) { this.nodeIndices.push(idx); } } }; /** * Set nodes and edges, and optionally options as well. * * @param {Object} data Object containing parameters: * {Array | DataSet | DataView} [nodes] Array with nodes * {Array | DataSet | DataView} [edges] Array with edges * {String} [dot] String containing data in DOT format * {String} [gephi] String containing data in gephi JSON format * {Options} [options] Object with options * @param {Boolean} [disableStart] | optional: disable the calling of the start function. */ Network.prototype.setData = function(data, disableStart) { if (disableStart === undefined) { disableStart = false; } if (data && data.dot && (data.nodes || data.edges)) { throw new SyntaxError('Data must contain either parameter "dot" or ' + ' parameter pair "nodes" and "edges", but not both.'); } // set options this.setOptions(data && data.options); // set all data if (data && data.dot) { // parse DOT file if(data && data.dot) { var dotData = dotparser.DOTToGraph(data.dot); this.setData(dotData); return; } } else if (data && data.gephi) { // parse DOT file if(data && data.gephi) { var gephiData = gephiParser.parseGephi(data.gephi); this.setData(gephiData); return; } } else { this._setNodes(data && data.nodes); this._setEdges(data && data.edges); } this._putDataInSector(); if (!disableStart) { // find a stable position or start animating to a stable position if (this.constants.stabilize) { var me = this; setTimeout(function() {me._stabilize(); me.start();},0) } else { this.start(); } } }; /** * Set options * @param {Object} options * @param {Boolean} [initializeView] | set zoom and translation to default. */ Network.prototype.setOptions = function (options) { if (options) { var prop; var fields = ['nodes','edges','smoothCurves','hierarchicalLayout','clustering','navigation','keyboard','dataManipulation', 'onAdd','onEdit','onEditEdge','onConnect','onDelete' ]; util.selectiveNotDeepExtend(fields,this.constants, options); util.selectiveNotDeepExtend(['color'],this.constants.nodes, options.nodes); util.selectiveNotDeepExtend(['color','length'],this.constants.edges, options.edges); if (options.physics) { util.mergeOptions(this.constants.physics, options.physics,'barnesHut'); util.mergeOptions(this.constants.physics, options.physics,'repulsion'); if (options.physics.hierarchicalRepulsion) { this.constants.hierarchicalLayout.enabled = true; this.constants.physics.hierarchicalRepulsion.enabled = true; this.constants.physics.barnesHut.enabled = false; for (prop in options.physics.hierarchicalRepulsion) { if (options.physics.hierarchicalRepulsion.hasOwnProperty(prop)) { this.constants.physics.hierarchicalRepulsion[prop] = options.physics.hierarchicalRepulsion[prop]; } } } } if (options.onAdd) {this.triggerFunctions.add = options.onAdd;} if (options.onEdit) {this.triggerFunctions.edit = options.onEdit;} if (options.onEditEdge) {this.triggerFunctions.editEdge = options.onEditEdge;} if (options.onConnect) {this.triggerFunctions.connect = options.onConnect;} if (options.onDelete) {this.triggerFunctions.del = options.onDelete;} util.mergeOptions(this.constants, options,'smoothCurves'); util.mergeOptions(this.constants, options,'hierarchicalLayout'); util.mergeOptions(this.constants, options,'clustering'); util.mergeOptions(this.constants, options,'navigation'); util.mergeOptions(this.constants, options,'keyboard'); util.mergeOptions(this.constants, options,'dataManipulation'); if (options.dataManipulation) { this.editMode = this.constants.dataManipulation.initiallyVisible; } // TODO: work out these options and document them if (options.edges) { if (options.edges.color !== undefined) { if (util.isString(options.edges.color)) { this.constants.edges.color = {}; this.constants.edges.color.color = options.edges.color; this.constants.edges.color.highlight = options.edges.color; this.constants.edges.color.hover = options.edges.color; } else { if (options.edges.color.color !== undefined) {this.constants.edges.color.color = options.edges.color.color;} if (options.edges.color.highlight !== undefined) {this.constants.edges.color.highlight = options.edges.color.highlight;} if (options.edges.color.hover !== undefined) {this.constants.edges.color.hover = options.edges.color.hover;} } } if (!options.edges.fontColor) { if (options.edges.color !== undefined) { if (util.isString(options.edges.color)) {this.constants.edges.fontColor = options.edges.color;} else if (options.edges.color.color !== undefined) {this.constants.edges.fontColor = options.edges.color.color;} } } } if (options.nodes) { if (options.nodes.color) { var newColorObj = util.parseColor(options.nodes.color); this.constants.nodes.color.background = newColorObj.background; this.constants.nodes.color.border = newColorObj.border; this.constants.nodes.color.highlight.background = newColorObj.highlight.background; this.constants.nodes.color.highlight.border = newColorObj.highlight.border; this.constants.nodes.color.hover.background = newColorObj.hover.background; this.constants.nodes.color.hover.border = newColorObj.hover.border; } } if (options.groups) { for (var groupname in options.groups) { if (options.groups.hasOwnProperty(groupname)) { var group = options.groups[groupname]; this.groups.add(groupname, group); } } } if (options.tooltip) { for (prop in options.tooltip) { if (options.tooltip.hasOwnProperty(prop)) { this.constants.tooltip[prop] = options.tooltip[prop]; } } if (options.tooltip.color) { this.constants.tooltip.color = util.parseColor(options.tooltip.color); } } } // (Re)loading the mixins that can be enabled or disabled in the options. // load the force calculation functions, grouped under the physics system. this._loadPhysicsSystem(); // load the navigation system. this._loadNavigationControls(); // load the data manipulation system this._loadManipulationSystem(); // configure the smooth curves this._configureSmoothCurves(); // bind keys. If disabled, this will not do anything; this._createKeyBinds(); this.setSize(this.constants.width, this.constants.height); this.moving = true; this.start(); }; /** * Create the main frame for the Network. * This function is executed once when a Network object is created. The frame * contains a canvas, and this canvas contains all objects like the axis and * nodes. * @private */ Network.prototype._create = function () { // remove all elements from the container element. while (this.containerElement.hasChildNodes()) { this.containerElement.removeChild(this.containerElement.firstChild); } this.frame = document.createElement('div'); this.frame.className = 'network-frame'; this.frame.style.position = 'relative'; this.frame.style.overflow = 'hidden'; // create the network canvas (HTML canvas element) this.frame.canvas = document.createElement( 'canvas' ); this.frame.canvas.style.position = 'relative'; this.frame.appendChild(this.frame.canvas); if (!this.frame.canvas.getContext) { var noCanvas = document.createElement( 'DIV' ); noCanvas.style.color = 'red'; noCanvas.style.fontWeight = 'bold' ; noCanvas.style.padding = '10px'; noCanvas.innerHTML = 'Error: your browser does not support HTML canvas'; this.frame.canvas.appendChild(noCanvas); } var me = this; this.drag = {}; this.pinch = {}; this.hammer = Hammer(this.frame.canvas, { prevent_default: true }); this.hammer.on('tap', me._onTap.bind(me) ); this.hammer.on('doubletap', me._onDoubleTap.bind(me) ); this.hammer.on('hold', me._onHold.bind(me) ); this.hammer.on('pinch', me._onPinch.bind(me) ); this.hammer.on('touch', me._onTouch.bind(me) ); this.hammer.on('dragstart', me._onDragStart.bind(me) ); this.hammer.on('drag', me._onDrag.bind(me) ); this.hammer.on('dragend', me._onDragEnd.bind(me) ); this.hammer.on('release', me._onRelease.bind(me) ); this.hammer.on('mousewheel',me._onMouseWheel.bind(me) ); this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) ); // add the frame to the container element this.containerElement.appendChild(this.frame); }; /** * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin * @private */ Network.prototype._createKeyBinds = function() { var me = this; this.mousetrap = mousetrap; this.mousetrap.reset(); if (this.constants.keyboard.enabled == true) { this.mousetrap.bind("up", this._moveUp.bind(me) , "keydown"); this.mousetrap.bind("up", this._yStopMoving.bind(me), "keyup"); this.mousetrap.bind("down", this._moveDown.bind(me) , "keydown"); this.mousetrap.bind("down", this._yStopMoving.bind(me), "keyup"); this.mousetrap.bind("left", this._moveLeft.bind(me) , "keydown"); this.mousetrap.bind("left", this._xStopMoving.bind(me), "keyup"); this.mousetrap.bind("right",this._moveRight.bind(me), "keydown"); this.mousetrap.bind("right",this._xStopMoving.bind(me), "keyup"); this.mousetrap.bind("=", this._zoomIn.bind(me), "keydown"); this.mousetrap.bind("=", this._stopZoom.bind(me), "keyup"); this.mousetrap.bind("-", this._zoomOut.bind(me), "keydown"); this.mousetrap.bind("-", this._stopZoom.bind(me), "keyup"); this.mousetrap.bind("[", this._zoomIn.bind(me), "keydown"); this.mousetrap.bind("[", this._stopZoom.bind(me), "keyup"); this.mousetrap.bind("]", this._zoomOut.bind(me), "keydown"); this.mousetrap.bind("]", this._stopZoom.bind(me), "keyup"); this.mousetrap.bind("pageup",this._zoomIn.bind(me), "keydown"); this.mousetrap.bind("pageup",this._stopZoom.bind(me), "keyup"); this.mousetrap.bind("pagedown",this._zoomOut.bind(me),"keydown"); this.mousetrap.bind("pagedown",this._stopZoom.bind(me), "keyup"); } if (this.constants.dataManipulation.enabled == true) { this.mousetrap.bind("escape",this._createManipulatorBar.bind(me)); this.mousetrap.bind("del",this._deleteSelected.bind(me)); } }; /** * Get the pointer location from a touch location * @param {{pageX: Number, pageY: Number}} touch * @return {{x: Number, y: Number}} pointer * @private */ Network.prototype._getPointer = function (touch) { return { x: touch.pageX - util.getAbsoluteLeft(this.frame.canvas), y: touch.pageY - util.getAbsoluteTop(this.frame.canvas) }; }; /** * On start of a touch gesture, store the pointer * @param event * @private */ Network.prototype._onTouch = function (event) { this.drag.pointer = this._getPointer(event.gesture.center); this.drag.pinched = false; this.pinch.scale = this._getScale(); this._handleTouch(this.drag.pointer); }; /** * handle drag start event * @private */ Network.prototype._onDragStart = function () { this._handleDragStart(); }; /** * This function is called by _onDragStart. * It is separated out because we can then overload it for the datamanipulation system. * * @private */ Network.prototype._handleDragStart = function() { var drag = this.drag; var node = this._getNodeAt(drag.pointer); // note: drag.pointer is set in _onTouch to get the initial touch location drag.dragging = true; drag.selection = []; drag.translation = this._getTranslation(); drag.nodeId = null; if (node != null) { drag.nodeId = node.id; // select the clicked node if not yet selected if (!node.isSelected()) { this._selectObject(node,false); } // create an array with the selected nodes and their original location and status for (var objectId in this.selectionObj.nodes) { if (this.selectionObj.nodes.hasOwnProperty(objectId)) { var object = this.selectionObj.nodes[objectId]; var s = { id: object.id, node: object, // store original x, y, xFixed and yFixed, make the node temporarily Fixed x: object.x, y: object.y, xFixed: object.xFixed, yFixed: object.yFixed }; object.xFixed = true; object.yFixed = true; drag.selection.push(s); } } } }; /** * handle drag event * @private */ Network.prototype._onDrag = function (event) { this._handleOnDrag(event) }; /** * This function is called by _onDrag. * It is separated out because we can then overload it for the datamanipulation system. * * @private */ Network.prototype._handleOnDrag = function(event) { if (this.drag.pinched) { return; } var pointer = this._getPointer(event.gesture.center); var me = this; var drag = this.drag; var selection = drag.selection; if (selection && selection.length && this.constants.dragNodes == true) { // calculate delta's and new location var deltaX = pointer.x - drag.pointer.x; var deltaY = pointer.y - drag.pointer.y; // update position of all selected nodes selection.forEach(function (s) { var node = s.node; if (!s.xFixed) { node.x = me._XconvertDOMtoCanvas(me._XconvertCanvasToDOM(s.x) + deltaX); } if (!s.yFixed) { node.y = me._YconvertDOMtoCanvas(me._YconvertCanvasToDOM(s.y) + deltaY); } }); // start _animationStep if not yet running if (!this.moving) { this.moving = true; this.start(); } } else { if (this.constants.dragNetwork == true) { // move the network var diffX = pointer.x - this.drag.pointer.x; var diffY = pointer.y - this.drag.pointer.y; this._setTranslation( this.drag.translation.x + diffX, this.drag.translation.y + diffY ); this._redraw(); // this.moving = true; // this.start(); } } }; /** * handle drag start event * @private */ Network.prototype._onDragEnd = function () { this.drag.dragging = false; var selection = this.drag.selection; if (selection && selection.length) { selection.forEach(function (s) { // restore original xFixed and yFixed s.node.xFixed = s.xFixed; s.node.yFixed = s.yFixed; }); this.moving = true; this.start(); } else { this._redraw(); } }; /** * handle tap/click event: select/unselect a node * @private */ Network.prototype._onTap = function (event) { var pointer = this._getPointer(event.gesture.center); this.pointerPosition = pointer; this._handleTap(pointer); }; /** * handle doubletap event * @private */ Network.prototype._onDoubleTap = function (event) { var pointer = this._getPointer(event.gesture.center); this._handleDoubleTap(pointer); }; /** * handle long tap event: multi select nodes * @private */ Network.prototype._onHold = function (event) { var pointer = this._getPointer(event.gesture.center); this.pointerPosition = pointer; this._handleOnHold(pointer); }; /** * handle the release of the screen * * @private */ Network.prototype._onRelease = function (event) { var pointer = this._getPointer(event.gesture.center); this._handleOnRelease(pointer); }; /** * Handle pinch event * @param event * @private */ Network.prototype._onPinch = function (event) { var pointer = this._getPointer(event.gesture.center); this.drag.pinched = true; if (!('scale' in this.pinch)) { this.pinch.scale = 1; } // TODO: enabled moving while pinching? var scale = this.pinch.scale * event.gesture.scale; this._zoom(scale, pointer) }; /** * Zoom the network in or out * @param {Number} scale a number around 1, and between 0.01 and 10 * @param {{x: Number, y: Number}} pointer Position on screen * @return {Number} appliedScale scale is limited within the boundaries * @private */ Network.prototype._zoom = function(scale, pointer) { if (this.constants.zoomable == true) { var scaleOld = this._getScale(); if (scale < 0.00001) { scale = 0.00001; } if (scale > 10) { scale = 10; } var preScaleDragPointer = null; if (this.drag !== undefined) { if (this.drag.dragging == true) { preScaleDragPointer = this.DOMtoCanvas(this.drag.pointer); } } // + this.frame.canvas.clientHeight / 2 var translation = this._getTranslation(); var scaleFrac = scale / scaleOld; var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac; var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac; this.areaCenter = {"x" : this._XconvertDOMtoCanvas(pointer.x), "y" : this._YconvertDOMtoCanvas(pointer.y)}; this._setScale(scale); this._setTranslation(tx, ty); this.updateClustersDefault(); if (preScaleDragPointer != null) { var postScaleDragPointer = this.canvasToDOM(preScaleDragPointer); this.drag.pointer.x = postScaleDragPointer.x; this.drag.pointer.y = postScaleDragPointer.y; } this._redraw(); if (scaleOld < scale) { this.emit("zoom", {direction:"+"}); } else { this.emit("zoom", {direction:"-"}); } return scale; } }; /** * Event handler for mouse wheel event, used to zoom the timeline * See http://adomas.org/javascript-mouse-wheel/ * https://github.com/EightMedia/hammer.js/issues/256 * @param {MouseEvent} event * @private */ Network.prototype._onMouseWheel = function(event) { // retrieve delta var delta = 0; if (event.wheelDelta) { /* IE/Opera. */ delta = event.wheelDelta/120; } else if (event.detail) { /* Mozilla case. */ // In Mozilla, sign of delta is different than in IE. // Also, delta is multiple of 3. delta = -event.detail/3; } // If delta is nonzero, handle it. // Basically, delta is now positive if wheel was scrolled up, // and negative, if wheel was scrolled down. if (delta) { // calculate the new scale var scale = this._getScale(); var zoom = delta / 10; if (delta < 0) { zoom = zoom / (1 - zoom); } scale *= (1 + zoom); // calculate the pointer location var gesture = hammerUtil.fakeGesture(this, event); var pointer = this._getPointer(gesture.center); // apply the new scale this._zoom(scale, pointer); } // Prevent default actions caused by mouse wheel. event.preventDefault(); }; /** * Mouse move handler for checking whether the title moves over a node with a title. * @param {Event} event * @private */ Network.prototype._onMouseMoveTitle = function (event) { var gesture = hammerUtil.fakeGesture(this, event); var pointer = this._getPointer(gesture.center); // check if the previously selected node is still selected if (this.popupObj) { this._checkHidePopup(pointer); } // start a timeout that will check if the mouse is positioned above // an element var me = this; var checkShow = function() { me._checkShowPopup(pointer); }; if (this.popupTimer) { clearInterval(this.popupTimer); // stop any running calculationTimer } if (!this.drag.dragging) { this.popupTimer = setTimeout(checkShow, this.constants.tooltip.delay); } /** * Adding hover highlights */ if (this.constants.hover == true) { // removing all hover highlights for (var edgeId in this.hoverObj.edges) { if (this.hoverObj.edges.hasOwnProperty(edgeId)) { this.hoverObj.edges[edgeId].hover = false; delete this.hoverObj.edges[edgeId]; } } // adding hover highlights var obj = this._getNodeAt(pointer); if (obj == null) { obj = this._getEdgeAt(pointer); } if (obj != null) { this._hoverObject(obj); } // removing all node hover highlights except for the selected one. for (var nodeId in this.hoverObj.nodes) { if (this.hoverObj.nodes.hasOwnProperty(nodeId)) { if (obj instanceof Node && obj.id != nodeId || obj instanceof Edge || obj == null) { this._blurObject(this.hoverObj.nodes[nodeId]); delete this.hoverObj.nodes[nodeId]; } } } this.redraw(); } }; /** * Check if there is an element on the given position in the network * (a node or edge). If so, and if this element has a title, * show a popup window with its title. * * @param {{x:Number, y:Number}} pointer * @private */ Network.prototype._checkShowPopup = function (pointer) { var obj = { left: this._XconvertDOMtoCanvas(pointer.x), top: this._YconvertDOMtoCanvas(pointer.y), right: this._XconvertDOMtoCanvas(pointer.x), bottom: this._YconvertDOMtoCanvas(pointer.y) }; var id; var lastPopupNode = this.popupObj; if (this.popupObj == undefined) { // search the nodes for overlap, select the top one in case of multiple nodes var nodes = this.nodes; for (id in nodes) { if (nodes.hasOwnProperty(id)) { var node = nodes[id]; if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) { this.popupObj = node; break; } } } } if (this.popupObj === undefined) { // search the edges for overlap var edges = this.edges; for (id in edges) { if (edges.hasOwnProperty(id)) { var edge = edges[id]; if (edge.connected && (edge.getTitle() !== undefined) && edge.isOverlappingWith(obj)) { this.popupObj = edge; break; } } } } if (this.popupObj) { // show popup message window if (this.popupObj != lastPopupNode) { var me = this; if (!me.popup) { me.popup = new Popup(me.frame, me.constants.tooltip); } // adjust a small offset such that the mouse cursor is located in the // bottom left location of the popup, and you can easily move over the // popup area me.popup.setPosition(pointer.x - 3, pointer.y - 3); me.popup.setText(me.popupObj.getTitle()); me.popup.show(); } } else { if (this.popup) { this.popup.hide(); } } }; /** * Check if the popup must be hided, which is the case when the mouse is no * longer hovering on the object * @param {{x:Number, y:Number}} pointer * @private */ Network.prototype._checkHidePopup = function (pointer) { if (!this.popupObj || !this._getNodeAt(pointer) ) { this.popupObj = undefined; if (this.popup) { this.popup.hide(); } } }; /** * Set a new size for the network * @param {string} width Width in pixels or percentage (for example '800px' * or '50%') * @param {string} height Height in pixels or percentage (for example '400px' * or '30%') */ Network.prototype.setSize = function(width, height) { this.frame.style.width = width; this.frame.style.height = height; this.frame.canvas.style.width = '100%'; this.frame.canvas.style.height = '100%'; this.frame.canvas.width = this.frame.canvas.clientWidth; this.frame.canvas.height = this.frame.canvas.clientHeight; if (this.manipulationDiv !== undefined) { this.manipulationDiv.style.width = this.frame.canvas.clientWidth + "px"; } if (this.navigationDivs !== undefined) { if (this.navigationDivs['wrapper'] !== undefined) { this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px"; this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px"; } } this.emit('resize', {width:this.frame.canvas.width,height:this.frame.canvas.height}); }; /** * Set a data set with nodes for the network * @param {Array | DataSet | DataView} nodes The data containing the nodes. * @private */ Network.prototype._setNodes = function(nodes) { var oldNodesData = this.nodesData; if (nodes instanceof DataSet || nodes instanceof DataView) { this.nodesData = nodes; } else if (nodes instanceof Array) { this.nodesData = new DataSet(); this.nodesData.add(nodes); } else if (!nodes) { this.nodesData = new DataSet(); } else { throw new TypeError('Array or DataSet expected'); } if (oldNodesData) { // unsubscribe from old dataset util.forEach(this.nodesListeners, function (callback, event) { oldNodesData.off(event, callback); }); } // remove drawn nodes this.nodes = {}; if (this.nodesData) { // subscribe to new dataset var me = this; util.forEach(this.nodesListeners, function (callback, event) { me.nodesData.on(event, callback); }); // draw all new nodes var ids = this.nodesData.getIds(); this._addNodes(ids); } this._updateSelection(); }; /** * Add nodes * @param {Number[] | String[]} ids * @private */ Network.prototype._addNodes = function(ids) { var id; for (var i = 0, len = ids.length; i < len; i++) { id = ids[i]; var data = this.nodesData.get(id); var node = new Node(data, this.images, this.groups, this.constants); this.nodes[id] = node; // note: this may replace an existing node if ((node.xFixed == false || node.yFixed == false) && (node.x === null || node.y === null)) { var radius = 10 * 0.1*ids.length; var angle = 2 * Math.PI * Math.random(); if (node.xFixed == false) {node.x = radius * Math.cos(angle);} if (node.yFixed == false) {node.y = radius * Math.sin(angle);} } this.moving = true; } this._updateNodeIndexList(); if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) { this._resetLevels(); this._setupHierarchicalLayout(); } this._updateCalculationNodes(); this._reconnectEdges(); this._updateValueRange(this.nodes); this.updateLabels(); }; /** * Update existing nodes, or create them when not yet existing * @param {Number[] | String[]} ids * @private */ Network.prototype._updateNodes = function(ids) { var nodes = this.nodes, nodesData = this.nodesData; for (var i = 0, len = ids.length; i < len; i++) { var id = ids[i]; var node = nodes[id]; var data = nodesData.get(id); if (node) { // update node node.setProperties(data, this.constants); } else { // create node node = new Node(properties, this.images, this.groups, this.constants); nodes[id] = node; } } this.moving = true; if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) { this._resetLevels(); this._setupHierarchicalLayout(); } this._updateNodeIndexList(); this._reconnectEdges(); this._updateValueRange(nodes); }; /** * Remove existing nodes. If nodes do not exist, the method will just ignore it. * @param {Number[] | String[]} ids * @private */ Network.prototype._removeNodes = function(ids) { var nodes = this.nodes; for (var i = 0, len = ids.length; i < len; i++) { var id = ids[i]; delete nodes[id]; } this._updateNodeIndexList(); if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) { this._resetLevels(); this._setupHierarchicalLayout(); } this._updateCalculationNodes(); this._reconnectEdges(); this._updateSelection(); this._updateValueRange(nodes); }; /** * Load edges by reading the data table * @param {Array | DataSet | DataView} edges The data containing the edges. * @private * @private */ Network.prototype._setEdges = function(edges) { var oldEdgesData = this.edgesData; if (edges instanceof DataSet || edges instanceof DataView) { this.edgesData = edges; } else if (edges instanceof Array) { this.edgesData = new DataSet(); this.edgesData.add(edges); } else if (!edges) { this.edgesData = new DataSet(); } else { throw new TypeError('Array or DataSet expected'); } if (oldEdgesData) { // unsubscribe from old dataset util.forEach(this.edgesListeners, function (callback, event) { oldEdgesData.off(event, callback); }); } // remove drawn edges this.edges = {}; if (this.edgesData) { // subscribe to new dataset var me = this; util.forEach(this.edgesListeners, function (callback, event) { me.edgesData.on(event, callback); }); // draw all new nodes var ids = this.edgesData.getIds(); this._addEdges(ids); } this._reconnectEdges(); }; /** * Add edges * @param {Number[] | String[]} ids * @private */ Network.prototype._addEdges = function (ids) { var edges = this.edges, edgesData = this.edgesData; for (var i = 0, len = ids.length; i < len; i++) { var id = ids[i]; var oldEdge = edges[id]; if (oldEdge) { oldEdge.disconnect(); } var data = edgesData.get(id, {"showInternalIds" : true}); edges[id] = new Edge(data, this, this.constants); } this.moving = true; this._updateValueRange(edges); this._createBezierNodes(); if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) { this._resetLevels(); this._setupHierarchicalLayout(); } this._updateCalculationNodes(); }; /** * Update existing edges, or create them when not yet existing * @param {Number[] | String[]} ids * @private */ Network.prototype._updateEdges = function (ids) { var edges = this.edges, edgesData = this.edgesData; for (var i = 0, len = ids.length; i < len; i++) { var id = ids[i]; var data = edgesData.get(id); var edge = edges[id]; if (edge) { // update edge edge.disconnect(); edge.setProperties(data, this.constants); edge.connect(); } else { // create edge edge = new Edge(data, this, this.constants); this.edges[id] = edge; } } this._createBezierNodes(); if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) { this._resetLevels(); this._setupHierarchicalLayout(); } this.moving = true; this._updateValueRange(edges); }; /** * Remove existing edges. Non existing ids will be ignored * @param {Number[] | String[]} ids * @private */ Network.prototype._removeEdges = function (ids) { var edges = this.edges; for (var i = 0, len = ids.length; i < len; i++) { var id = ids[i]; var edge = edges[id]; if (edge) { if (edge.via != null) { delete this.sectors['support']['nodes'][edge.via.id]; } edge.disconnect(); delete edges[id]; } } this.moving = true; this._updateValueRange(edges); if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) { this._resetLevels(); this._setupHierarchicalLayout(); } this._updateCalculationNodes(); }; /** * Reconnect all edges * @private */ Network.prototype._reconnectEdges = function() { var id, nodes = this.nodes, edges = this.edges; for (id in nodes) { if (nodes.hasOwnProperty(id)) { nodes[id].edges = []; } } for (id in edges) { if (edges.hasOwnProperty(id)) { var edge = edges[id]; edge.from = null; edge.to = null; edge.connect(); } } }; /** * Update the values of all object in the given array according to the current * value range of the objects in the array. * @param {Object} obj An object containing a set of Edges or Nodes * The objects must have a method getValue() and * setValueRange(min, max). * @private */ Network.prototype._updateValueRange = function(obj) { var id; // determine the range of the objects var valueMin = undefined; var valueMax = undefined; for (id in obj) { if (obj.hasOwnProperty(id)) { var value = obj[id].getValue(); if (value !== undefined) { valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin); valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax); } } } // adjust the range of all objects if (valueMin !== undefined && valueMax !== undefined) { for (id in obj) { if (obj.hasOwnProperty(id)) { obj[id].setValueRange(valueMin, valueMax); } } } }; /** * Redraw the network with the current data * chart will be resized too. */ Network.prototype.redraw = function() { this.setSize(this.constants.width, this.constants.height); this._redraw(); }; /** * Redraw the network with the current data * @private */ Network.prototype._redraw = function() { var ctx = this.frame.canvas.getContext('2d'); // clear the canvas var w = this.frame.canvas.width; var h = this.frame.canvas.height; ctx.clearRect(0, 0, w, h); // set scaling and translation ctx.save(); ctx.translate(this.translation.x, this.translation.y); ctx.scale(this.scale, this.scale); this.canvasTopLeft = { "x": this._XconvertDOMtoCanvas(0), "y": this._YconvertDOMtoCanvas(0) }; this.canvasBottomRight = { "x": this._XconvertDOMtoCanvas(this.frame.canvas.clientWidth), "y": this._YconvertDOMtoCanvas(this.frame.canvas.clientHeight) }; this._doInAllSectors("_drawAllSectorNodes",ctx); if (this.drag.dragging == false || this.drag.dragging === undefined || this.constants.hideEdgesOnDrag == false) { this._doInAllSectors("_drawEdges",ctx); } if (this.drag.dragging == false || this.drag.dragging === undefined || this.constants.hideNodesOnDrag == false) { this._doInAllSectors("_drawNodes",ctx,false); } if (this.controlNodesActive == true) { this._doInAllSectors("_drawControlNodes",ctx); } // this._doInSupportSector("_drawNodes",ctx,true); // this._drawTree(ctx,"#F00F0F"); // restore original scaling and translation ctx.restore(); }; /** * Set the translation of the network * @param {Number} offsetX Horizontal offset * @param {Number} offsetY Vertical offset * @private */ Network.prototype._setTranslation = function(offsetX, offsetY) { if (this.translation === undefined) { this.translation = { x: 0, y: 0 }; } if (offsetX !== undefined) { this.translation.x = offsetX; } if (offsetY !== undefined) { this.translation.y = offsetY; } this.emit('viewChanged'); }; /** * Get the translation of the network * @return {Object} translation An object with parameters x and y, both a number * @private */ Network.prototype._getTranslation = function() { return { x: this.translation.x, y: this.translation.y }; }; /** * Scale the network * @param {Number} scale Scaling factor 1.0 is unscaled * @private */ Network.prototype._setScale = function(scale) { this.scale = scale; }; /** * Get the current scale of the network * @return {Number} scale Scaling factor 1.0 is unscaled * @private */ Network.prototype._getScale = function() { return this.scale; }; /** * Convert the X coordinate in DOM-space (coordinate point in browser relative to the container div) to * the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) * @param {number} x * @returns {number} * @private */ Network.prototype._XconvertDOMtoCanvas = function(x) { return (x - this.translation.x) / this.scale; }; /** * Convert the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to * the X coordinate in DOM-space (coordinate point in browser relative to the container div) * @param {number} x * @returns {number} * @private */ Network.prototype._XconvertCanvasToDOM = function(x) { return x * this.scale + this.translation.x; }; /** * Convert the Y coordinate in DOM-space (coordinate point in browser relative to the container div) to * the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) * @param {number} y * @returns {number} * @private */ Network.prototype._YconvertDOMtoCanvas = function(y) { return (y - this.translation.y) / this.scale; }; /** * Convert the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to * the Y coordinate in DOM-space (coordinate point in browser relative to the container div) * @param {number} y * @returns {number} * @private */ Network.prototype._YconvertCanvasToDOM = function(y) { return y * this.scale + this.translation.y ; }; /** * * @param {object} pos = {x: number, y: number} * @returns {{x: number, y: number}} * @constructor */ Network.prototype.canvasToDOM = function(pos) { return {x:this._XconvertCanvasToDOM(pos.x),y:this._YconvertCanvasToDOM(pos.y)}; } /** * * @param {object} pos = {x: number, y: number} * @returns {{x: number, y: number}} * @constructor */ Network.prototype.DOMtoCanvas = function(pos) { return {x:this._XconvertDOMtoCanvas(pos.x),y:this._YconvertDOMtoCanvas(pos.y)}; } /** * Redraw all nodes * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); * @param {CanvasRenderingContext2D} ctx * @param {Boolean} [alwaysShow] * @private */ Network.prototype._drawNodes = function(ctx,alwaysShow) { if (alwaysShow === undefined) { alwaysShow = false; } // first draw the unselected nodes var nodes = this.nodes; var selected = []; for (var id in nodes) { if (nodes.hasOwnProperty(id)) { nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight); if (nodes[id].isSelected()) { selected.push(id); } else { if (nodes[id].inArea() || alwaysShow) { nodes[id].draw(ctx); } } } } // draw the selected nodes on top for (var s = 0, sMax = selected.length; s < sMax; s++) { if (nodes[selected[s]].inArea() || alwaysShow) { nodes[selected[s]].draw(ctx); } } }; /** * Redraw all edges * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); * @param {CanvasRenderingContext2D} ctx * @private */ Network.prototype._drawEdges = function(ctx) { var edges = this.edges; for (var id in edges) { if (edges.hasOwnProperty(id)) { var edge = edges[id]; edge.setScale(this.scale); if (edge.connected) { edges[id].draw(ctx); } } } }; /** * Redraw all edges * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); * @param {CanvasRenderingContext2D} ctx * @private */ Network.prototype._drawControlNodes = function(ctx) { var edges = this.edges; for (var id in edges) { if (edges.hasOwnProperty(id)) { edges[id]._drawControlNodes(ctx); } } }; /** * Find a stable position for all nodes * @private */ Network.prototype._stabilize = function() { if (this.constants.freezeForStabilization == true) { this._freezeDefinedNodes(); } // find stable position var count = 0; while (this.moving && count < this.constants.stabilizationIterations) { this._physicsTick(); count++; } this.zoomExtent(false,true); if (this.constants.freezeForStabilization == true) { this._restoreFrozenNodes(); } this.emit("stabilized",{iterations:count}); }; /** * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization * because only the supportnodes for the smoothCurves have to settle. * * @private */ Network.prototype._freezeDefinedNodes = function() { var nodes = this.nodes; for (var id in nodes) { if (nodes.hasOwnProperty(id)) { if (nodes[id].x != null && nodes[id].y != null) { nodes[id].fixedData.x = nodes[id].xFixed; nodes[id].fixedData.y = nodes[id].yFixed; nodes[id].xFixed = true; nodes[id].yFixed = true; } } } }; /** * Unfreezes the nodes that have been frozen by _freezeDefinedNodes. * * @private */ Network.prototype._restoreFrozenNodes = function() { var nodes = this.nodes; for (var id in nodes) { if (nodes.hasOwnProperty(id)) { if (nodes[id].fixedData.x != null) { nodes[id].xFixed = nodes[id].fixedData.x; nodes[id].yFixed = nodes[id].fixedData.y; } } } }; /** * Check if any of the nodes is still moving * @param {number} vmin the minimum velocity considered as 'moving' * @return {boolean} true if moving, false if non of the nodes is moving * @private */ Network.prototype._isMoving = function(vmin) { var nodes = this.nodes; for (var id in nodes) { if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) { return true; } } return false; }; /** * /** * Perform one discrete step for all nodes * * @private */ Network.prototype._discreteStepNodes = function() { var interval = this.physicsDiscreteStepsize; var nodes = this.nodes; var nodeId; var nodesPresent = false; if (this.constants.maxVelocity > 0) { for (nodeId in nodes) { if (nodes.hasOwnProperty(nodeId)) { nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity); nodesPresent = true; } } } else { for (nodeId in nodes) { if (nodes.hasOwnProperty(nodeId)) { nodes[nodeId].discreteStep(interval); nodesPresent = true; } } } if (nodesPresent == true) { var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05); if (vminCorrected > 0.5*this.constants.maxVelocity) { this.moving = true; } else { this.moving = this._isMoving(vminCorrected); if (this.moving == false) { this.emit("stabilized",{iterations:null}); } this.moving = this.moving || this.configurePhysics; } } }; /** * A single simulation step (or "tick") in the physics simulation * * @private */ Network.prototype._physicsTick = function() { if (!this.freezeSimulation) { if (this.moving == true) { this._doInAllActiveSectors("_initializeForceCalculation"); this._doInAllActiveSectors("_discreteStepNodes"); if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) { this._doInSupportSector("_discreteStepNodes"); } this._findCenter(this._getRange()) } } }; /** * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick. * It reschedules itself at the beginning of the function * * @private */ Network.prototype._animationStep = function() { // reset the timer so a new scheduled animation step can be set this.timer = undefined; // handle the keyboad movement this._handleNavigation(); // this schedules a new animation step this.start(); // start the physics simulation var calculationTime = Date.now(); var maxSteps = 1; this._physicsTick(); var timeRequired = Date.now() - calculationTime; while (timeRequired < 0.9*(this.renderTimestep - this.renderTime) && maxSteps < this.maxPhysicsTicksPerRender) { this._physicsTick(); timeRequired = Date.now() - calculationTime; maxSteps++; } // start the rendering process var renderTime = Date.now(); this._redraw(); this.renderTime = Date.now() - renderTime; }; if (typeof window !== 'undefined') { window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; } /** * Schedule a animation step with the refreshrate interval. */ Network.prototype.start = function() { if (this.moving == true || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) { if (!this.timer) { var ua = navigator.userAgent.toLowerCase(); var requiresTimeout = false; if (ua.indexOf('msie 9.0') != -1) { // IE 9 requiresTimeout = true; } else if (ua.indexOf('safari') != -1) { // safari if (ua.indexOf('chrome') <= -1) { requiresTimeout = true; } } if (requiresTimeout == true) { this.timer = window.setTimeout(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function } else{ this.timer = window.requestAnimationFrame(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function } } } else { this._redraw(); } }; /** * Move the network according to the keyboard presses. * * @private */ Network.prototype._handleNavigation = function() { if (this.xIncrement != 0 || this.yIncrement != 0) { var translation = this._getTranslation(); this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement); } if (this.zoomIncrement != 0) { var center = { x: this.frame.canvas.clientWidth / 2, y: this.frame.canvas.clientHeight / 2 }; this._zoom(this.scale*(1 + this.zoomIncrement), center); } }; /** * Freeze the _animationStep */ Network.prototype.toggleFreeze = function() { if (this.freezeSimulation == false) { this.freezeSimulation = true; } else { this.freezeSimulation = false; this.start(); } }; /** * This function cleans the support nodes if they are not needed and adds them when they are. * * @param {boolean} [disableStart] * @private */ Network.prototype._configureSmoothCurves = function(disableStart) { if (disableStart === undefined) { disableStart = true; } if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) { this._createBezierNodes(); // cleanup unused support nodes for (var nodeId in this.sectors['support']['nodes']) { if (this.sectors['support']['nodes'].hasOwnProperty(nodeId)) { if (this.edges[this.sectors['support']['nodes'][nodeId].parentEdgeId] === undefined) { delete this.sectors['support']['nodes'][nodeId]; } } } } else { // delete the support nodes this.sectors['support']['nodes'] = {}; for (var edgeId in this.edges) { if (this.edges.hasOwnProperty(edgeId)) { this.edges[edgeId].via = null; } } } this._updateCalculationNodes(); if (!disableStart) { this.moving = true; this.start(); } }; /** * Bezier curves require an anchor point to calculate the smooth flow. These points are nodes. These nodes are invisible but * are used for the force calculation. * * @private */ Network.prototype._createBezierNodes = function() { if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) { for (var edgeId in this.edges) { if (this.edges.hasOwnProperty(edgeId)) { var edge = this.edges[edgeId]; if (edge.via == null) { var nodeId = "edgeId:".concat(edge.id); this.sectors['support']['nodes'][nodeId] = new Node( {id:nodeId, mass:1, shape:'circle', image:"", internalMultiplier:1 },{},{},this.constants); edge.via = this.sectors['support']['nodes'][nodeId]; edge.via.parentEdgeId = edge.id; edge.positionBezierNode(); } } } } }; /** * load the functions that load the mixins into the prototype. * * @private */ Network.prototype._initializeMixinLoaders = function () { for (var mixin in MixinLoader) { if (MixinLoader.hasOwnProperty(mixin)) { Network.prototype[mixin] = MixinLoader[mixin]; } } }; /** * Load the XY positions of the nodes into the dataset. */ Network.prototype.storePosition = function() { var dataArray = []; for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { var node = this.nodes[nodeId]; var allowedToMoveX = !this.nodes.xFixed; var allowedToMoveY = !this.nodes.yFixed; if (this.nodesData._data[nodeId].x != Math.round(node.x) || this.nodesData._data[nodeId].y != Math.round(node.y)) { dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY}); } } } this.nodesData.update(dataArray); }; /** * Center a node in view. * * @param {Number} nodeId * @param {Number} [zoomLevel] */ Network.prototype.focusOnNode = function (nodeId, zoomLevel) { if (this.nodes.hasOwnProperty(nodeId)) { if (zoomLevel === undefined) { zoomLevel = this._getScale(); } var nodePosition= {x: this.nodes[nodeId].x, y: this.nodes[nodeId].y}; var requiredScale = zoomLevel; this._setScale(requiredScale); var canvasCenter = this.DOMtoCanvas({x:0.5 * this.frame.canvas.width,y:0.5 * this.frame.canvas.height}); var translation = this._getTranslation(); var distanceFromCenter = {x:canvasCenter.x - nodePosition.x, y:canvasCenter.y - nodePosition.y}; this._setTranslation(translation.x + requiredScale * distanceFromCenter.x, translation.y + requiredScale * distanceFromCenter.y); this.redraw(); } else { console.log("This nodeId cannot be found.") } }; module.exports = Network; /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var Node = __webpack_require__(36); /** * @class Edge * * A edge connects two nodes * @param {Object} properties Object with properties. Must contain * At least properties from and to. * Available properties: from (number), * to (number), label (string, color (string), * width (number), style (string), * length (number), title (string) * @param {Network} network A Network object, used to find and edge to * nodes. * @param {Object} constants An object with default values for * example for the color */ function Edge (properties, network, networkConstants) { if (!network) { throw "No network provided"; } var fields = ['edges','physics']; var constants = util.selectiveBridgeObject(fields,networkConstants); this.options = constants.edges; this.physics = constants.physics; this.options['smoothCurves'] = networkConstants['smoothCurves']; this.network = network; // initialize variables this.id = undefined; this.fromId = undefined; this.toId = undefined; this.title = undefined; this.widthSelected = this.options.width * this.options.widthSelectionMultiplier; this.value = undefined; this.selected = false; this.hover = false; this.from = null; // a node this.to = null; // a node this.via = null; // a temp node // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster // by storing the original information we can revert to the original connection when the cluser is opened. this.originalFromId = []; this.originalToId = []; this.connected = false; this.widthFixed = false; this.lengthFixed = false; this.setProperties(properties); this.controlNodesEnabled = false; this.controlNodes = {from:null, to:null, positions:{}}; this.connectedNode = null; } /** * Set or overwrite properties for the edge * @param {Object} properties an object with properties * @param {Object} constants and object with default, global properties */ Edge.prototype.setProperties = function(properties) { if (!properties) { return; } var fields = ['style','fontSize','fontFace','fontColor','fontFill','width', 'widthSelectionMultiplier','hoverWidth','arrowScaleFactor','dash' ]; util.selectiveDeepExtend(fields, this.options, properties); if (properties.from !== undefined) {this.fromId = properties.from;} if (properties.to !== undefined) {this.toId = properties.to;} if (properties.id !== undefined) {this.id = properties.id;} if (properties.label !== undefined) {this.label = properties.label;} if (properties.title !== undefined) {this.title = properties.title;} if (properties.value !== undefined) {this.value = properties.value;} if (properties.length !== undefined) {this.physics.springLength = properties.length;} // scale the arrow if (properties.arrowScaleFactor !== undefined) {this.options.arrowScaleFactor = properties.arrowScaleFactor;} if (properties.inheritColor !== undefined) {this.options.inheritColor = properties.inheritColor;} if (properties.color !== undefined) { this.options.inheritColor = false; if (util.isString(properties.color)) { this.options.color.color = properties.color; this.options.color.highlight = properties.color; } else { if (properties.color.color !== undefined) {this.options.color.color = properties.color.color;} if (properties.color.highlight !== undefined) {this.options.color.highlight = properties.color.highlight;} if (properties.color.hover !== undefined) {this.options.color.hover = properties.color.hover;} } } // A node is connected when it has a from and to node. this.connect(); this.widthFixed = this.widthFixed || (properties.width !== undefined); this.lengthFixed = this.lengthFixed || (properties.length !== undefined); this.widthSelected = this.options.width* this.options.widthSelectionMultiplier; // set draw method based on style switch (this.options.style) { case 'line': this.draw = this._drawLine; break; case 'arrow': this.draw = this._drawArrow; break; case 'arrow-center': this.draw = this._drawArrowCenter; break; case 'dash-line': this.draw = this._drawDashLine; break; default: this.draw = this._drawLine; break; } }; /** * Connect an edge to its nodes */ Edge.prototype.connect = function () { this.disconnect(); this.from = this.network.nodes[this.fromId] || null; this.to = this.network.nodes[this.toId] || null; this.connected = (this.from && this.to); if (this.connected) { this.from.attachEdge(this); this.to.attachEdge(this); } else { if (this.from) { this.from.detachEdge(this); } if (this.to) { this.to.detachEdge(this); } } }; /** * Disconnect an edge from its nodes */ Edge.prototype.disconnect = function () { if (this.from) { this.from.detachEdge(this); this.from = null; } if (this.to) { this.to.detachEdge(this); this.to = null; } this.connected = false; }; /** * get the title of this edge. * @return {string} title The title of the edge, or undefined when no title * has been set. */ Edge.prototype.getTitle = function() { return typeof this.title === "function" ? this.title() : this.title; }; /** * Retrieve the value of the edge. Can be undefined * @return {Number} value */ Edge.prototype.getValue = function() { return this.value; }; /** * Adjust the value range of the edge. The edge will adjust it's width * based on its value. * @param {Number} min * @param {Number} max */ Edge.prototype.setValueRange = function(min, max) { if (!this.widthFixed && this.value !== undefined) { var scale = (this.options.widthMax - this.options.widthMin) / (max - min); this.options.width= (this.value - min) * scale + this.options.widthMin; this.widthSelected = this.options.width* this.options.widthSelectionMultiplier; } }; /** * Redraw a edge * Draw this edge in the given canvas * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); * @param {CanvasRenderingContext2D} ctx */ Edge.prototype.draw = function(ctx) { throw "Method draw not initialized in edge"; }; /** * Check if this object is overlapping with the provided object * @param {Object} obj an object with parameters left, top * @return {boolean} True if location is located on the edge */ Edge.prototype.isOverlappingWith = function(obj) { if (this.connected) { var distMax = 10; var xFrom = this.from.x; var yFrom = this.from.y; var xTo = this.to.x; var yTo = this.to.y; var xObj = obj.left; var yObj = obj.top; var dist = this._getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj); return (dist < distMax); } else { return false } }; Edge.prototype._getColor = function() { var colorObj = this.options.color; if (this.options.inheritColor == "to") { colorObj = { highlight: this.to.options.color.highlight.border, hover: this.to.options.color.hover.border, color: this.to.options.color.border }; } else if (this.options.inheritColor == "from" || this.options.inheritColor == true) { colorObj = { highlight: this.from.options.color.highlight.border, hover: this.from.options.color.hover.border, color: this.from.options.color.border }; } if (this.selected == true) {return colorObj.highlight;} else if (this.hover == true) {return colorObj.hover;} else {return colorObj.color;} } /** * Redraw a edge as a line * Draw this edge in the given canvas * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); * @param {CanvasRenderingContext2D} ctx * @private */ Edge.prototype._drawLine = function(ctx) { // set style ctx.strokeStyle = this._getColor(); ctx.lineWidth = this._getLineWidth(); if (this.from != this.to) { // draw line var via = this._line(ctx); // draw label var point; if (this.label) { if (this.options.smoothCurves.enabled == true && via != null) { var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x)); var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y)); point = {x:midpointX, y:midpointY}; } else { point = this._pointOnLine(0.5); } this._label(ctx, this.label, point.x, point.y); } } else { var x, y; var radius = this.physics.springLength / 4; var node = this.from; if (!node.width) { node.resize(ctx); } if (node.width > node.height) { x = node.x + node.width / 2; y = node.y - radius; } else { x = node.x + radius; y = node.y - node.height / 2; } this._circle(ctx, x, y, radius); point = this._pointOnCircle(x, y, radius, 0.5); this._label(ctx, this.label, point.x, point.y); } }; /** * Get the line width of the edge. Depends on width and whether one of the * connected nodes is selected. * @return {Number} width * @private */ Edge.prototype._getLineWidth = function() { if (this.selected == true) { return Math.min(this.widthSelected, this.options.widthMax)*this.networkScaleInv; } else { if (this.hover == true) { return Math.min(this.options.hoverWidth, this.options.widthMax)*this.networkScaleInv; } else { return this.options.width*this.networkScaleInv; } } }; Edge.prototype._getViaCoordinates = function () { var xVia = null; var yVia = null; var factor = this.options.smoothCurves.roundness; var type = this.options.smoothCurves.type; var dx = Math.abs(this.from.x - this.to.x); var dy = Math.abs(this.from.y - this.to.y); if (type == 'discrete' || type == 'diagonalCross') { if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) { if (this.from.y > this.to.y) { if (this.from.x < this.to.x) { xVia = this.from.x + factor * dy; yVia = this.from.y - factor * dy; } else if (this.from.x > this.to.x) { xVia = this.from.x - factor * dy; yVia = this.from.y - factor * dy; } } else if (this.from.y < this.to.y) { if (this.from.x < this.to.x) { xVia = this.from.x + factor * dy; yVia = this.from.y + factor * dy; } else if (this.from.x > this.to.x) { xVia = this.from.x - factor * dy; yVia = this.from.y + factor * dy; } } if (type == "discrete") { xVia = dx < factor * dy ? this.from.x : xVia; } } else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) { if (this.from.y > this.to.y) { if (this.from.x < this.to.x) { xVia = this.from.x + factor * dx; yVia = this.from.y - factor * dx; } else if (this.from.x > this.to.x) { xVia = this.from.x - factor * dx; yVia = this.from.y - factor * dx; } } else if (this.from.y < this.to.y) { if (this.from.x < this.to.x) { xVia = this.from.x + factor * dx; yVia = this.from.y + factor * dx; } else if (this.from.x > this.to.x) { xVia = this.from.x - factor * dx; yVia = this.from.y + factor * dx; } } if (type == "discrete") { yVia = dy < factor * dx ? this.from.y : yVia; } } } else if (type == "straightCross") { if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) { // up - down xVia = this.from.x; if (this.from.y < this.to.y) { yVia = this.to.y - (1-factor) * dy; } else { yVia = this.to.y + (1-factor) * dy; } } else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) { // left - right if (this.from.x < this.to.x) { xVia = this.to.x - (1-factor) * dx; } else { xVia = this.to.x + (1-factor) * dx; } yVia = this.from.y; } } else if (type == 'horizontal') { if (this.from.x < this.to.x) { xVia = this.to.x - (1-factor) * dx; } else { xVia = this.to.x + (1-factor) * dx; } yVia = this.from.y; } else if (type == 'vertical') { xVia = this.from.x; if (this.from.y < this.to.y) { yVia = this.to.y - (1-factor) * dy; } else { yVia = this.to.y + (1-factor) * dy; } } else { // continuous if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) { if (this.from.y > this.to.y) { if (this.from.x < this.to.x) { // console.log(1) xVia = this.from.x + factor * dy; yVia = this.from.y - factor * dy; xVia = this.to.x < xVia ? this.to.x : xVia; } else if (this.from.x > this.to.x) { // console.log(2) xVia = this.from.x - factor * dy; yVia = this.from.y - factor * dy; xVia = this.to.x > xVia ? this.to.x :xVia; } } else if (this.from.y < this.to.y) { if (this.from.x < this.to.x) { // console.log(3) xVia = this.from.x + factor * dy; yVia = this.from.y + factor * dy; xVia = this.to.x < xVia ? this.to.x : xVia; } else if (this.from.x > this.to.x) { // console.log(4, this.from.x, this.to.x) xVia = this.from.x - factor * dy; yVia = this.from.y + factor * dy; xVia = this.to.x > xVia ? this.to.x : xVia; } } } else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) { if (this.from.y > this.to.y) { if (this.from.x < this.to.x) { // console.log(5) xVia = this.from.x + factor * dx; yVia = this.from.y - factor * dx; yVia = this.to.y > yVia ? this.to.y : yVia; } else if (this.from.x > this.to.x) { // console.log(6) xVia = this.from.x - factor * dx; yVia = this.from.y - factor * dx; yVia = this.to.y > yVia ? this.to.y : yVia; } } else if (this.from.y < this.to.y) { if (this.from.x < this.to.x) { // console.log(7) xVia = this.from.x + factor * dx; yVia = this.from.y + factor * dx; yVia = this.to.y < yVia ? this.to.y : yVia; } else if (this.from.x > this.to.x) { // console.log(8) xVia = this.from.x - factor * dx; yVia = this.from.y + factor * dx; yVia = this.to.y < yVia ? this.to.y : yVia; } } } } return {x:xVia, y:yVia}; } /** * Draw a line between two nodes * @param {CanvasRenderingContext2D} ctx * @private */ Edge.prototype._line = function (ctx) { // draw a straight line ctx.beginPath(); ctx.moveTo(this.from.x, this.from.y); if (this.options.smoothCurves.enabled == true) { if (this.options.smoothCurves.dynamic == false) { var via = this._getViaCoordinates(); if (via.x == null) { ctx.lineTo(this.to.x, this.to.y); ctx.stroke(); return null; } else { // this.via.x = via.x; // this.via.y = via.y; ctx.quadraticCurveTo(via.x,via.y,this.to.x, this.to.y); ctx.stroke(); return via; } } else { ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y); ctx.stroke(); return this.via; } } else { ctx.lineTo(this.to.x, this.to.y); ctx.stroke(); return null; } }; /** * Draw a line from a node to itself, a circle * @param {CanvasRenderingContext2D} ctx * @param {Number} x * @param {Number} y * @param {Number} radius * @private */ Edge.prototype._circle = function (ctx, x, y, radius) { // draw a circle ctx.beginPath(); ctx.arc(x, y, radius, 0, 2 * Math.PI, false); ctx.stroke(); }; /** * Draw label with white background and with the middle at (x, y) * @param {CanvasRenderingContext2D} ctx * @param {String} text * @param {Number} x * @param {Number} y * @private */ Edge.prototype._label = function (ctx, text, x, y) { if (text) { // TODO: cache the calculated size ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") + this.options.fontSize + "px " + this.options.fontFace; ctx.fillStyle = this.options.fontFill; var width = ctx.measureText(text).width; var height = this.options.fontSize; var left = x - width / 2; var top = y - height / 2; ctx.fillRect(left, top, width, height); // draw text ctx.fillStyle = this.options.fontColor || "black"; ctx.textAlign = "left"; ctx.textBaseline = "top"; ctx.fillText(text, left, top); } }; /** * Redraw a edge as a dashed line * Draw this edge in the given canvas * @author David Jordan * @date 2012-08-08 * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); * @param {CanvasRenderingContext2D} ctx * @private */ Edge.prototype._drawDashLine = function(ctx) { // set style if (this.selected == true) {ctx.strokeStyle = this.options.color.highlight;} else if (this.hover == true) {ctx.strokeStyle = this.options.color.hover;} else {ctx.strokeStyle = this.options.color.color;} ctx.lineWidth = this._getLineWidth(); var via = null; // only firefox and chrome support this method, else we use the legacy one. if (ctx.mozDash !== undefined || ctx.setLineDash !== undefined) { // configure the dash pattern var pattern = [0]; if (this.options.dash.length !== undefined && this.options.dash.gap !== undefined) { pattern = [this.options.dash.length,this.options.dash.gap]; } else { pattern = [5,5]; } // set dash settings for chrome or firefox if (typeof ctx.setLineDash !== 'undefined') { //Chrome ctx.setLineDash(pattern); ctx.lineDashOffset = 0; } else { //Firefox ctx.mozDash = pattern; ctx.mozDashOffset = 0; } // draw the line via = this._line(ctx); // restore the dash settings. if (typeof ctx.setLineDash !== 'undefined') { //Chrome ctx.setLineDash([0]); ctx.lineDashOffset = 0; } else { //Firefox ctx.mozDash = [0]; ctx.mozDashOffset = 0; } } else { // unsupporting smooth lines // draw dashed line ctx.beginPath(); ctx.lineCap = 'round'; if (this.options.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value { ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y, [this.options.dash.length,this.options.dash.gap,this.options.dash.altLength,this.options.dash.gap]); } else if (this.options.dash.length !== undefined && this.options.dash.gap !== undefined) //If a dash and gap value has been set add to the array this value { ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y, [this.options.dash.length,this.options.dash.gap]); } else //If all else fails draw a line { ctx.moveTo(this.from.x, this.from.y); ctx.lineTo(this.to.x, this.to.y); } ctx.stroke(); } // draw label if (this.label) { var point; if (this.options.smoothCurves.enabled == true && via != null) { var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x)); var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y)); point = {x:midpointX, y:midpointY}; } else { point = this._pointOnLine(0.5); } this._label(ctx, this.label, point.x, point.y); } }; /** * Get a point on a line * @param {Number} percentage. Value between 0 (line start) and 1 (line end) * @return {Object} point * @private */ Edge.prototype._pointOnLine = function (percentage) { return { x: (1 - percentage) * this.from.x + percentage * this.to.x, y: (1 - percentage) * this.from.y + percentage * this.to.y } }; /** * Get a point on a circle * @param {Number} x * @param {Number} y * @param {Number} radius * @param {Number} percentage. Value between 0 (line start) and 1 (line end) * @return {Object} point * @private */ Edge.prototype._pointOnCircle = function (x, y, radius, percentage) { var angle = (percentage - 3/8) * 2 * Math.PI; return { x: x + radius * Math.cos(angle), y: y - radius * Math.sin(angle) } }; /** * Redraw a edge as a line with an arrow halfway the line * Draw this edge in the given canvas * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); * @param {CanvasRenderingContext2D} ctx * @private */ Edge.prototype._drawArrowCenter = function(ctx) { var point; // set style if (this.selected == true) {ctx.strokeStyle = this.options.color.highlight; ctx.fillStyle = this.options.color.highlight;} else if (this.hover == true) {ctx.strokeStyle = this.options.color.hover; ctx.fillStyle = this.options.color.hover;} else {ctx.strokeStyle = this.options.color.color; ctx.fillStyle = this.options.color.color;} ctx.lineWidth = this._getLineWidth(); if (this.from != this.to) { // draw line var via = this._line(ctx); var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x)); var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor; // draw an arrow halfway the line if (this.options.smoothCurves.enabled == true && via != null) { var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x)); var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y)); point = {x:midpointX, y:midpointY}; } else { point = this._pointOnLine(0.5); } ctx.arrow(point.x, point.y, angle, length); ctx.fill(); ctx.stroke(); // draw label if (this.label) { this._label(ctx, this.label, point.x, point.y); } } else { // draw circle var x, y; var radius = 0.25 * Math.max(100,this.physics.springLength); var node = this.from; if (!node.width) { node.resize(ctx); } if (node.width > node.height) { x = node.x + node.width * 0.5; y = node.y - radius; } else { x = node.x + radius; y = node.y - node.height * 0.5; } this._circle(ctx, x, y, radius); // draw all arrows var angle = 0.2 * Math.PI; var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor; point = this._pointOnCircle(x, y, radius, 0.5); ctx.arrow(point.x, point.y, angle, length); ctx.fill(); ctx.stroke(); // draw label if (this.label) { point = this._pointOnCircle(x, y, radius, 0.5); this._label(ctx, this.label, point.x, point.y); } } }; /** * Redraw a edge as a line with an arrow * Draw this edge in the given canvas * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); * @param {CanvasRenderingContext2D} ctx * @private */ Edge.prototype._drawArrow = function(ctx) { // set style if (this.selected == true) {ctx.strokeStyle = this.options.color.highlight; ctx.fillStyle = this.options.color.highlight;} else if (this.hover == true) {ctx.strokeStyle = this.options.color.hover; ctx.fillStyle = this.options.color.hover;} else {ctx.strokeStyle = this.options.color.color; ctx.fillStyle = this.options.color.color;} ctx.lineWidth = this._getLineWidth(); var angle, length; //draw a line if (this.from != this.to) { angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x)); var dx = (this.to.x - this.from.x); var dy = (this.to.y - this.from.y); var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy); var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI); var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength; var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x; var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y; var via; if (this.options.smoothCurves.dynamic == true && this.options.smoothCurves.enabled == true ) { via = this.via; } else if (this.options.smoothCurves.enabled == true) { via = this._getViaCoordinates(); } if (this.options.smoothCurves.enabled == true && via.x != null) { angle = Math.atan2((this.to.y - via.y), (this.to.x - via.x)); dx = (this.to.x - via.x); dy = (this.to.y - via.y); edgeSegmentLength = Math.sqrt(dx * dx + dy * dy); } var toBorderDist = this.to.distanceToBorder(ctx, angle); var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength; var xTo,yTo; if (this.options.smoothCurves.enabled == true && via.x != null) { xTo = (1 - toBorderPoint) * via.x + toBorderPoint * this.to.x; yTo = (1 - toBorderPoint) * via.y + toBorderPoint * this.to.y; } else { xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x; yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y; } ctx.beginPath(); ctx.moveTo(xFrom,yFrom); if (this.options.smoothCurves.enabled == true && via.x != null) { ctx.quadraticCurveTo(via.x,via.y,xTo, yTo); } else { ctx.lineTo(xTo, yTo); } ctx.stroke(); // draw arrow at the end of the line length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor; ctx.arrow(xTo, yTo, angle, length); ctx.fill(); ctx.stroke(); // draw label if (this.label) { var point; if (this.options.smoothCurves.enabled == true && via != null) { var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x)); var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y)); point = {x:midpointX, y:midpointY}; } else { point = this._pointOnLine(0.5); } this._label(ctx, this.label, point.x, point.y); } } else { // draw circle var node = this.from; var x, y, arrow; var radius = 0.25 * Math.max(100,this.physics.springLength); if (!node.width) { node.resize(ctx); } if (node.width > node.height) { x = node.x + node.width * 0.5; y = node.y - radius; arrow = { x: x, y: node.y, angle: 0.9 * Math.PI }; } else { x = node.x + radius; y = node.y - node.height * 0.5; arrow = { x: node.x, y: y, angle: 0.6 * Math.PI }; } ctx.beginPath(); // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center ctx.arc(x, y, radius, 0, 2 * Math.PI, false); ctx.stroke(); // draw all arrows var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor; ctx.arrow(arrow.x, arrow.y, arrow.angle, length); ctx.fill(); ctx.stroke(); // draw label if (this.label) { point = this._pointOnCircle(x, y, radius, 0.5); this._label(ctx, this.label, point.x, point.y); } } }; /** * Calculate the distance between a point (x3,y3) and a line segment from * (x1,y1) to (x2,y2). * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment * @param {number} x1 * @param {number} y1 * @param {number} x2 * @param {number} y2 * @param {number} x3 * @param {number} y3 * @private */ Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point if (this.from != this.to) { if (this.options.smoothCurves.enabled == true) { var xVia, yVia; if (this.options.smoothCurves.enabled == true && this.options.smoothCurves.dynamic == true) { xVia = this.via.x; yVia = this.via.y; } else { var via = this._getViaCoordinates(); xVia = via.x; yVia = via.y; } var minDistance = 1e9; var distance; var i,t,x,y, lastX, lastY; for (i = 0; i < 10; i++) { t = 0.1*i; x = Math.pow(1-t,2)*x1 + (2*t*(1 - t))*xVia + Math.pow(t,2)*x2; y = Math.pow(1-t,2)*y1 + (2*t*(1 - t))*yVia + Math.pow(t,2)*y2; if (i > 0) { distance = this._getDistanceToLine(lastX,lastY,x,y, x3,y3); minDistance = distance < minDistance ? distance : minDistance; } lastX = x; lastY = y; } return minDistance } else { return this._getDistanceToLine(x1,y1,x2,y2,x3,y3); } } else { var x, y, dx, dy; var radius = this.physics.springLength / 4; var node = this.from; if (!node.width) { node.resize(ctx); } if (node.width > node.height) { x = node.x + node.width / 2; y = node.y - radius; } else { x = node.x + radius; y = node.y - node.height / 2; } dx = x - x3; dy = y - y3; return Math.abs(Math.sqrt(dx*dx + dy*dy) - radius); } }; Edge.prototype._getDistanceToLine = function(x1,y1,x2,y2,x3,y3) { var px = x2-x1, py = y2-y1, something = px*px + py*py, u = ((x3 - x1) * px + (y3 - y1) * py) / something; if (u > 1) { u = 1; } else if (u < 0) { u = 0; } var x = x1 + u * px, y = y1 + u * py, dx = x - x3, dy = y - y3; //# Note: If the actual distance does not matter, //# if you only want to compare what this function //# returns to other results of this function, you //# can just return the squared distance instead //# (i.e. remove the sqrt) to gain a little performance return Math.sqrt(dx*dx + dy*dy); } /** * This allows the zoom level of the network to influence the rendering * * @param scale */ Edge.prototype.setScale = function(scale) { this.networkScaleInv = 1.0/scale; }; Edge.prototype.select = function() { this.selected = true; }; Edge.prototype.unselect = function() { this.selected = false; }; Edge.prototype.positionBezierNode = function() { if (this.via !== null && this.from !== null && this.to !== null) { this.via.x = 0.5 * (this.from.x + this.to.x); this.via.y = 0.5 * (this.from.y + this.to.y); } }; /** * This function draws the control nodes for the manipulator. In order to enable this, only set the this.controlNodesEnabled to true. * @param ctx */ Edge.prototype._drawControlNodes = function(ctx) { if (this.controlNodesEnabled == true) { if (this.controlNodes.from === null && this.controlNodes.to === null) { var nodeIdFrom = "edgeIdFrom:".concat(this.id); var nodeIdTo = "edgeIdTo:".concat(this.id); var constants = { nodes:{group:'', radius:8}, physics:{damping:0}, clustering: {maxNodeSizeIncrements: 0 ,nodeScaling: {width:0, height: 0, radius:0}} }; this.controlNodes.from = new Node( {id:nodeIdFrom, shape:'dot', color:{background:'#ff4e00', border:'#3c3c3c', highlight: {background:'#07f968'}} },{},{},constants); this.controlNodes.to = new Node( {id:nodeIdTo, shape:'dot', color:{background:'#ff4e00', border:'#3c3c3c', highlight: {background:'#07f968'}} },{},{},constants); } if (this.controlNodes.from.selected == false && this.controlNodes.to.selected == false) { this.controlNodes.positions = this.getControlNodePositions(ctx); this.controlNodes.from.x = this.controlNodes.positions.from.x; this.controlNodes.from.y = this.controlNodes.positions.from.y; this.controlNodes.to.x = this.controlNodes.positions.to.x; this.controlNodes.to.y = this.controlNodes.positions.to.y; } this.controlNodes.from.draw(ctx); this.controlNodes.to.draw(ctx); } else { this.controlNodes = {from:null, to:null, positions:{}}; } }; /** * Enable control nodes. * @private */ Edge.prototype._enableControlNodes = function() { this.controlNodesEnabled = true; }; /** * disable control nodes * @private */ Edge.prototype._disableControlNodes = function() { this.controlNodesEnabled = false; }; /** * This checks if one of the control nodes is selected and if so, returns the control node object. Else it returns null. * @param x * @param y * @returns {null} * @private */ Edge.prototype._getSelectedControlNode = function(x,y) { var positions = this.controlNodes.positions; var fromDistance = Math.sqrt(Math.pow(x - positions.from.x,2) + Math.pow(y - positions.from.y,2)); var toDistance = Math.sqrt(Math.pow(x - positions.to.x ,2) + Math.pow(y - positions.to.y ,2)); if (fromDistance < 15) { this.connectedNode = this.from; this.from = this.controlNodes.from; return this.controlNodes.from; } else if (toDistance < 15) { this.connectedNode = this.to; this.to = this.controlNodes.to; return this.controlNodes.to; } else { return null; } }; /** * this resets the control nodes to their original position. * @private */ Edge.prototype._restoreControlNodes = function() { if (this.controlNodes.from.selected == true) { this.from = this.connectedNode; this.connectedNode = null; this.controlNodes.from.unselect(); } if (this.controlNodes.to.selected == true) { this.to = this.connectedNode; this.connectedNode = null; this.controlNodes.to.unselect(); } }; /** * this calculates the position of the control nodes on the edges of the parent nodes. * * @param ctx * @returns {{from: {x: number, y: number}, to: {x: *, y: *}}} */ Edge.prototype.getControlNodePositions = function(ctx) { var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x)); var dx = (this.to.x - this.from.x); var dy = (this.to.y - this.from.y); var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy); var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI); var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength; var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x; var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y; var via; if (this.options.smoothCurves.dynamic == true && this.options.smoothCurves.enabled == true) { via = this.via; } else if (this.options.smoothCurves.enabled == true) { via = this._getViaCoordinates(); } if (this.options.smoothCurves.enabled == true && via.x != null) { angle = Math.atan2((this.to.y - via.y), (this.to.x - via.x)); dx = (this.to.x - via.x); dy = (this.to.y - via.y); edgeSegmentLength = Math.sqrt(dx * dx + dy * dy); } var toBorderDist = this.to.distanceToBorder(ctx, angle); var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength; var xTo,yTo; if (this.options.smoothCurves.enabled == true && via.x != null) { xTo = (1 - toBorderPoint) * via.x + toBorderPoint * this.to.x; yTo = (1 - toBorderPoint) * via.y + toBorderPoint * this.to.y; } else { xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x; yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y; } return {from:{x:xFrom,y:yFrom},to:{x:xTo,y:yTo}}; }; module.exports = Edge; /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); /** * @class Groups * This class can store groups and properties specific for groups. */ function Groups() { this.clear(); this.defaultIndex = 0; } /** * default constants for group colors */ Groups.DEFAULT = [ {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}, hover: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}, hover: {border: "#FFA500", background: "#FFFFA3"}}, // yellow {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}, hover: {border: "#FA0A10", background: "#FFAFB1"}}, // red {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}, hover: {border: "#41A906", background: "#A1EC76"}}, // green {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}, hover: {border: "#E129F0", background: "#F0B3F5"}}, // magenta {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}, hover: {border: "#7C29F0", background: "#D3BDF0"}}, // purple {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}, hover: {border: "#C37F00", background: "#FFCA66"}}, // orange {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}, hover: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}, hover: {border: "#FD5A77", background: "#FFD1D9"}}, // pink {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}, hover: {border: "#4AD63A", background: "#E6FFE3"}} // mint ]; /** * Clear all groups */ Groups.prototype.clear = function () { this.groups = {}; this.groups.length = function() { var i = 0; for ( var p in this ) { if (this.hasOwnProperty(p)) { i++; } } return i; } }; /** * get group properties of a groupname. If groupname is not found, a new group * is added. * @param {*} groupname Can be a number, string, Date, etc. * @return {Object} group The created group, containing all group properties */ Groups.prototype.get = function (groupname) { var group = this.groups[groupname]; if (group == undefined) { // create new group var index = this.defaultIndex % Groups.DEFAULT.length; this.defaultIndex++; group = {}; group.color = Groups.DEFAULT[index]; this.groups[groupname] = group; } return group; }; /** * Add a custom group style * @param {String} groupname * @param {Object} style An object containing borderColor, * backgroundColor, etc. * @return {Object} group The created group object */ Groups.prototype.add = function (groupname, style) { this.groups[groupname] = style; if (style.color) { style.color = util.parseColor(style.color); } return style; }; module.exports = Groups; /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { /** * @class Images * This class loads images and keeps them stored. */ function Images() { this.images = {}; this.callback = undefined; } /** * Set an onload callback function. This will be called each time an image * is loaded * @param {function} callback */ Images.prototype.setOnloadCallback = function(callback) { this.callback = callback; }; /** * * @param {string} url Url of the image * @return {Image} img The image object */ Images.prototype.load = function(url) { var img = this.images[url]; if (img == undefined) { // create the image var images = this; img = new Image(); this.images[url] = img; img.onload = function() { if (images.callback) { images.callback(this); } }; img.src = url; } return img; }; module.exports = Images; /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); /** * @class Node * A node. A node can be connected to other nodes via one or multiple edges. * @param {object} properties An object containing properties for the node. All * properties are optional, except for the id. * {number} id Id of the node. Required * {string} label Text label for the node * {number} x Horizontal position of the node * {number} y Vertical position of the node * {string} shape Node shape, available: * "database", "circle", "ellipse", * "box", "image", "text", "dot", * "star", "triangle", "triangleDown", * "square" * {string} image An image url * {string} title An title text, can be HTML * {anytype} group A group name or number * @param {Network.Images} imagelist A list with images. Only needed * when the node has an image * @param {Network.Groups} grouplist A list with groups. Needed for * retrieving group properties * @param {Object} constants An object with default values for * example for the color * */ function Node(properties, imagelist, grouplist, networkConstants) { var constants = util.selectiveBridgeObject(['nodes'],networkConstants); this.options = constants.nodes; this.selected = false; this.hover = false; this.edges = []; // all edges connected to this node this.dynamicEdges = []; this.reroutedEdges = {}; this.fontDrawThreshold = 3; // set defaults for the properties this.id = undefined; this.x = null; this.y = null; this.xFixed = false; this.yFixed = false; this.horizontalAlignLeft = true; // these are for the navigation controls this.verticalAlignTop = true; // these are for the navigation controls this.baseRadiusValue = networkConstants.nodes.radius; this.radiusFixed = false; this.level = -1; this.preassignedLevel = false; this.imagelist = imagelist; this.grouplist = grouplist; // physics properties this.fx = 0.0; // external force x this.fy = 0.0; // external force y this.vx = 0.0; // velocity x this.vy = 0.0; // velocity y this.damping = networkConstants.physics.damping; // written every time gravity is calculated this.fixedData = {x:null,y:null}; this.setProperties(properties, constants); // creating the variables for clustering this.resetCluster(); this.dynamicEdgesLength = 0; this.clusterSession = 0; this.clusterSizeWidthFactor = networkConstants.clustering.nodeScaling.width; this.clusterSizeHeightFactor = networkConstants.clustering.nodeScaling.height; this.clusterSizeRadiusFactor = networkConstants.clustering.nodeScaling.radius; this.maxNodeSizeIncrements = networkConstants.clustering.maxNodeSizeIncrements; this.growthIndicator = 0; // variables to tell the node about the network. this.networkScaleInv = 1; this.networkScale = 1; this.canvasTopLeft = {"x": -300, "y": -300}; this.canvasBottomRight = {"x": 300, "y": 300}; this.parentEdgeId = null; } /** * (re)setting the clustering variables and objects */ Node.prototype.resetCluster = function() { // clustering variables this.formationScale = undefined; // this is used to determine when to open the cluster this.clusterSize = 1; // this signifies the total amount of nodes in this cluster this.containedNodes = {}; this.containedEdges = {}; this.clusterSessions = []; }; /** * Attach a edge to the node * @param {Edge} edge */ Node.prototype.attachEdge = function(edge) { if (this.edges.indexOf(edge) == -1) { this.edges.push(edge); } if (this.dynamicEdges.indexOf(edge) == -1) { this.dynamicEdges.push(edge); } this.dynamicEdgesLength = this.dynamicEdges.length; }; /** * Detach a edge from the node * @param {Edge} edge */ Node.prototype.detachEdge = function(edge) { var index = this.edges.indexOf(edge); if (index != -1) { this.edges.splice(index, 1); this.dynamicEdges.splice(index, 1); } this.dynamicEdgesLength = this.dynamicEdges.length; }; /** * Set or overwrite properties for the node * @param {Object} properties an object with properties * @param {Object} constants and object with default, global properties */ Node.prototype.setProperties = function(properties, constants) { if (!properties) { return; } var fields = ['borderWidth','borderWidthSelected','shape','image','radius','fontColor', 'fontSize','fontFace','group','mass' ]; util.selectiveDeepExtend(fields, this.options, properties); this.originalLabel = undefined; // basic properties if (properties.id !== undefined) {this.id = properties.id;} if (properties.label !== undefined) {this.label = properties.label; this.originalLabel = properties.label;} if (properties.title !== undefined) {this.title = properties.title;} if (properties.x !== undefined) {this.x = properties.x;} if (properties.y !== undefined) {this.y = properties.y;} if (properties.value !== undefined) {this.value = properties.value;} if (properties.level !== undefined) {this.level = properties.level; this.preassignedLevel = true;} // navigation controls properties if (properties.horizontalAlignLeft !== undefined) {this.horizontalAlignLeft = properties.horizontalAlignLeft;} if (properties.verticalAlignTop !== undefined) {this.verticalAlignTop = properties.verticalAlignTop;} if (properties.triggerFunction !== undefined) {this.triggerFunction = properties.triggerFunction;} if (this.id === undefined) { throw "Node must have an id"; } // console.log(this.options); // copy group properties if (this.options.group !== undefined && this.options.group != "") { var groupObj = this.grouplist.get(this.options.group); for (var prop in groupObj) { if (groupObj.hasOwnProperty(prop)) { this.options[prop] = groupObj[prop]; } } } // individual shape properties if (properties.radius !== undefined) {this.baseRadiusValue = this.options.radius;} if (properties.color !== undefined) {this.options.color = util.parseColor(properties.color);} if (this.options.image!== undefined && this.options.image!= "") { if (this.imagelist) { this.imageObj = this.imagelist.load(this.options.image); } else { throw "No imagelist provided"; } } this.xFixed = this.xFixed || (properties.x !== undefined && !properties.allowedToMoveX); this.yFixed = this.yFixed || (properties.y !== undefined && !properties.allowedToMoveY); this.radiusFixed = this.radiusFixed || (properties.radius !== undefined); if (this.options.shape == 'image') { this.options.radiusMin = constants.nodes.widthMin; this.options.radiusMax = constants.nodes.widthMax; } // choose draw method depending on the shape switch (this.options.shape) { case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break; case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break; case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break; case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break; // TODO: add diamond shape case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break; case 'text': this.draw = this._drawText; this.resize = this._resizeText; break; case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break; case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break; case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break; case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break; case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break; default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break; } // reset the size of the node, this can be changed this._reset(); }; /** * select this node */ Node.prototype.select = function() { this.selected = true; this._reset(); }; /** * unselect this node */ Node.prototype.unselect = function() { this.selected = false; this._reset(); }; /** * Reset the calculated size of the node, forces it to recalculate its size */ Node.prototype.clearSizeCache = function() { this._reset(); }; /** * Reset the calculated size of the node, forces it to recalculate its size * @private */ Node.prototype._reset = function() { this.width = undefined; this.height = undefined; }; /** * get the title of this node. * @return {string} title The title of the node, or undefined when no title * has been set. */ Node.prototype.getTitle = function() { return typeof this.title === "function" ? this.title() : this.title; }; /** * Calculate the distance to the border of the Node * @param {CanvasRenderingContext2D} ctx * @param {Number} angle Angle in radians * @returns {number} distance Distance to the border in pixels */ Node.prototype.distanceToBorder = function (ctx, angle) { var borderWidth = 1; if (!this.width) { this.resize(ctx); } switch (this.options.shape) { case 'circle': case 'dot': return this.options.radius+ borderWidth; case 'ellipse': var a = this.width / 2; var b = this.height / 2; var w = (Math.sin(angle) * a); var h = (Math.cos(angle) * b); return a * b / Math.sqrt(w * w + h * h); // TODO: implement distanceToBorder for database // TODO: implement distanceToBorder for triangle // TODO: implement distanceToBorder for triangleDown case 'box': case 'image': case 'text': default: if (this.width) { return Math.min( Math.abs(this.width / 2 / Math.cos(angle)), Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth; // TODO: reckon with border radius too in case of box } else { return 0; } } // TODO: implement calculation of distance to border for all shapes }; /** * Set forces acting on the node * @param {number} fx Force in horizontal direction * @param {number} fy Force in vertical direction */ Node.prototype._setForce = function(fx, fy) { this.fx = fx; this.fy = fy; }; /** * Add forces acting on the node * @param {number} fx Force in horizontal direction * @param {number} fy Force in vertical direction * @private */ Node.prototype._addForce = function(fx, fy) { this.fx += fx; this.fy += fy; }; /** * Perform one discrete step for the node * @param {number} interval Time interval in seconds */ Node.prototype.discreteStep = function(interval) { if (!this.xFixed) { var dx = this.damping * this.vx; // damping force var ax = (this.fx - dx) / this.options.mass; // acceleration this.vx += ax * interval; // velocity this.x += this.vx * interval; // position } if (!this.yFixed) { var dy = this.damping * this.vy; // damping force var ay = (this.fy - dy) / this.options.mass; // acceleration this.vy += ay * interval; // velocity this.y += this.vy * interval; // position } }; /** * Perform one discrete step for the node * @param {number} interval Time interval in seconds * @param {number} maxVelocity The speed limit imposed on the velocity */ Node.prototype.discreteStepLimited = function(interval, maxVelocity) { if (!this.xFixed) { var dx = this.damping * this.vx; // damping force var ax = (this.fx - dx) / this.options.mass; // acceleration this.vx += ax * interval; // velocity this.vx = (Math.abs(this.vx) > maxVelocity) ? ((this.vx > 0) ? maxVelocity : -maxVelocity) : this.vx; this.x += this.vx * interval; // position } else { this.fx = 0; } if (!this.yFixed) { var dy = this.damping * this.vy; // damping force var ay = (this.fy - dy) / this.options.mass; // acceleration this.vy += ay * interval; // velocity this.vy = (Math.abs(this.vy) > maxVelocity) ? ((this.vy > 0) ? maxVelocity : -maxVelocity) : this.vy; this.y += this.vy * interval; // position } else { this.fy = 0; } }; /** * Check if this node has a fixed x and y position * @return {boolean} true if fixed, false if not */ Node.prototype.isFixed = function() { return (this.xFixed && this.yFixed); }; /** * Check if this node is moving * @param {number} vmin the minimum velocity considered as "moving" * @return {boolean} true if moving, false if it has no velocity */ // TODO: replace this method with calculating the kinetic energy Node.prototype.isMoving = function(vmin) { return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin); }; /** * check if this node is selecte * @return {boolean} selected True if node is selected, else false */ Node.prototype.isSelected = function() { return this.selected; }; /** * Retrieve the value of the node. Can be undefined * @return {Number} value */ Node.prototype.getValue = function() { return this.value; }; /** * Calculate the distance from the nodes location to the given location (x,y) * @param {Number} x * @param {Number} y * @return {Number} value */ Node.prototype.getDistance = function(x, y) { var dx = this.x - x, dy = this.y - y; return Math.sqrt(dx * dx + dy * dy); }; /** * Adjust the value range of the node. The node will adjust it's radius * based on its value. * @param {Number} min * @param {Number} max */ Node.prototype.setValueRange = function(min, max) { if (!this.radiusFixed && this.value !== undefined) { if (max == min) { this.options.radius= (this.options.radiusMin + this.options.radiusMax) / 2; } else { var scale = (this.options.radiusMax - this.options.radiusMin) / (max - min); this.options.radius= (this.value - min) * scale + this.options.radiusMin; } } this.baseRadiusValue = this.options.radius; }; /** * Draw this node in the given canvas * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); * @param {CanvasRenderingContext2D} ctx */ Node.prototype.draw = function(ctx) { throw "Draw method not initialized for node"; }; /** * Recalculate the size of this node in the given canvas * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); * @param {CanvasRenderingContext2D} ctx */ Node.prototype.resize = function(ctx) { throw "Resize method not initialized for node"; }; /** * Check if this object is overlapping with the provided object * @param {Object} obj an object with parameters left, top, right, bottom * @return {boolean} True if location is located on node */ Node.prototype.isOverlappingWith = function(obj) { return (this.left < obj.right && this.left + this.width > obj.left && this.top < obj.bottom && this.top + this.height > obj.top); }; Node.prototype._resizeImage = function (ctx) { // TODO: pre calculate the image size if (!this.width || !this.height) { // undefined or 0 var width, height; if (this.value) { this.options.radius= this.baseRadiusValue; var scale = this.imageObj.height / this.imageObj.width; if (scale !== undefined) { width = this.options.radius|| this.imageObj.width; height = this.options.radius* scale || this.imageObj.height; } else { width = 0; height = 0; } } else { width = this.imageObj.width; height = this.imageObj.height; } this.width = width; this.height = height; this.growthIndicator = 0; if (this.width > 0 && this.height > 0) { this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor; this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor; this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor; this.growthIndicator = this.width - width; } } }; Node.prototype._drawImage = function (ctx) { this._resizeImage(ctx); this.left = this.x - this.width / 2; this.top = this.y - this.height / 2; var yLabel; if (this.imageObj.width != 0 ) { // draw the shade if (this.clusterSize > 1) { var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0); lineWidth *= this.networkScaleInv; lineWidth = Math.min(0.2 * this.width,lineWidth); ctx.globalAlpha = 0.5; ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth); } // draw the image ctx.globalAlpha = 1.0; ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height); yLabel = this.y + this.height / 2; } else { // image still loading... just draw the label for now yLabel = this.y; } this._label(ctx, this.label, this.x, yLabel, undefined, "top"); }; Node.prototype._resizeBox = function (ctx) { if (!this.width) { var margin = 5; var textSize = this.getTextSize(ctx); this.width = textSize.width + 2 * margin; this.height = textSize.height + 2 * margin; this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor; this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor; this.growthIndicator = this.width - (textSize.width + 2 * margin); // this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor; } }; Node.prototype._drawBox = function (ctx) { this._resizeBox(ctx); this.left = this.x - this.width / 2; this.top = this.y - this.height / 2; var clusterLineWidth = 2.5; var borderWidth = this.options.borderWidth; var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border; // draw the outer border if (this.clusterSize > 1) { ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.networkScaleInv; ctx.lineWidth = Math.min(this.width,ctx.lineWidth); ctx.roundRect(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth, this.options.radius); ctx.stroke(); } ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.networkScaleInv; ctx.lineWidth = Math.min(this.width,ctx.lineWidth); ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.options.color.background; ctx.roundRect(this.left, this.top, this.width, this.height, this.options.radius); ctx.fill(); ctx.stroke(); this._label(ctx, this.label, this.x, this.y); }; Node.prototype._resizeDatabase = function (ctx) { if (!this.width) { var margin = 5; var textSize = this.getTextSize(ctx); var size = textSize.width + 2 * margin; this.width = size; this.height = size; // scaling used for clustering this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor; this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor; this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor; this.growthIndicator = this.width - size; } }; Node.prototype._drawDatabase = function (ctx) { this._resizeDatabase(ctx); this.left = this.x - this.width / 2; this.top = this.y - this.height / 2; var clusterLineWidth = 2.5; var borderWidth = this.options.borderWidth; var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border; // draw the outer border if (this.clusterSize > 1) { ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.networkScaleInv; ctx.lineWidth = Math.min(this.width,ctx.lineWidth); ctx.database(this.x - this.width/2 - 2*ctx.lineWidth, this.y - this.height*0.5 - 2*ctx.lineWidth, this.width + 4*ctx.lineWidth, this.height + 4*ctx.lineWidth); ctx.stroke(); } ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.networkScaleInv; ctx.lineWidth = Math.min(this.width,ctx.lineWidth); ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background; ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height); ctx.fill(); ctx.stroke(); this._label(ctx, this.label, this.x, this.y); }; Node.prototype._resizeCircle = function (ctx) { if (!this.width) { var margin = 5; var textSize = this.getTextSize(ctx); var diameter = Math.max(textSize.width, textSize.height) + 2 * margin; this.options.radius= diameter / 2; this.width = diameter; this.height = diameter; // scaling used for clustering // this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor; // this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor; this.options.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor; this.growthIndicator = this.options.radius- 0.5*diameter; } }; Node.prototype._drawCircle = function (ctx) { this._resizeCircle(ctx); this.left = this.x - this.width / 2; this.top = this.y - this.height / 2; var clusterLineWidth = 2.5; var borderWidth = this.options.borderWidth; var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border; // draw the outer border if (this.clusterSize > 1) { ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.networkScaleInv; ctx.lineWidth = Math.min(this.width,ctx.lineWidth); ctx.circle(this.x, this.y, this.options.radius+2*ctx.lineWidth); ctx.stroke(); } ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.networkScaleInv; ctx.lineWidth = Math.min(this.width,ctx.lineWidth); ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background; ctx.circle(this.x, this.y, this.options.radius); ctx.fill(); ctx.stroke(); this._label(ctx, this.label, this.x, this.y); }; Node.prototype._resizeEllipse = function (ctx) { if (!this.width) { var textSize = this.getTextSize(ctx); this.width = textSize.width * 1.5; this.height = textSize.height * 2; if (this.width < this.height) { this.width = this.height; } var defaultSize = this.width; // scaling used for clustering this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor; this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor; this.options.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor; this.growthIndicator = this.width - defaultSize; } }; Node.prototype._drawEllipse = function (ctx) { this._resizeEllipse(ctx); this.left = this.x - this.width / 2; this.top = this.y - this.height / 2; var clusterLineWidth = 2.5; var borderWidth = this.options.borderWidth; var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border; // draw the outer border if (this.clusterSize > 1) { ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.networkScaleInv; ctx.lineWidth = Math.min(this.width,ctx.lineWidth); ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth); ctx.stroke(); } ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.networkScaleInv; ctx.lineWidth = Math.min(this.width,ctx.lineWidth); ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background; ctx.ellipse(this.left, this.top, this.width, this.height); ctx.fill(); ctx.stroke(); this._label(ctx, this.label, this.x, this.y); }; Node.prototype._drawDot = function (ctx) { this._drawShape(ctx, 'circle'); }; Node.prototype._drawTriangle = function (ctx) { this._drawShape(ctx, 'triangle'); }; Node.prototype._drawTriangleDown = function (ctx) { this._drawShape(ctx, 'triangleDown'); }; Node.prototype._drawSquare = function (ctx) { this._drawShape(ctx, 'square'); }; Node.prototype._drawStar = function (ctx) { this._drawShape(ctx, 'star'); }; Node.prototype._resizeShape = function (ctx) { if (!this.width) { this.options.radius= this.baseRadiusValue; var size = 2 * this.options.radius; this.width = size; this.height = size; // scaling used for clustering this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor; this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor; this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor; this.growthIndicator = this.width - size; } }; Node.prototype._drawShape = function (ctx, shape) { this._resizeShape(ctx); this.left = this.x - this.width / 2; this.top = this.y - this.height / 2; var clusterLineWidth = 2.5; var borderWidth = this.options.borderWidth; var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; var radiusMultiplier = 2; // choose draw method depending on the shape switch (shape) { case 'dot': radiusMultiplier = 2; break; case 'square': radiusMultiplier = 2; break; case 'triangle': radiusMultiplier = 3; break; case 'triangleDown': radiusMultiplier = 3; break; case 'star': radiusMultiplier = 4; break; } ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border; // draw the outer border if (this.clusterSize > 1) { ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.networkScaleInv; ctx.lineWidth = Math.min(this.width,ctx.lineWidth); ctx[shape](this.x, this.y, this.options.radius+ radiusMultiplier * ctx.lineWidth); ctx.stroke(); } ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.networkScaleInv; ctx.lineWidth = Math.min(this.width,ctx.lineWidth); ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background; ctx[shape](this.x, this.y, this.options.radius); ctx.fill(); ctx.stroke(); if (this.label) { this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top',true); } }; Node.prototype._resizeText = function (ctx) { if (!this.width) { var margin = 5; var textSize = this.getTextSize(ctx); this.width = textSize.width + 2 * margin; this.height = textSize.height + 2 * margin; // scaling used for clustering this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor; this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor; this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor; this.growthIndicator = this.width - (textSize.width + 2 * margin); } }; Node.prototype._drawText = function (ctx) { this._resizeText(ctx); this.left = this.x - this.width / 2; this.top = this.y - this.height / 2; this._label(ctx, this.label, this.x, this.y); }; Node.prototype._label = function (ctx, text, x, y, align, baseline, labelUnderNode) { if (text && Number(this.options.fontSize) * this.networkScale > this.fontDrawThreshold) { ctx.font = (this.selected ? "bold " : "") + this.options.fontSize + "px " + this.options.fontFace; ctx.fillStyle = this.options.fontColor || "black"; ctx.textAlign = align || "center"; ctx.textBaseline = baseline || "middle"; var lines = text.split('\n'); var lineCount = lines.length; var fontSize = (Number(this.options.fontSize) + 4); var yLine = y + (1 - lineCount) / 2 * fontSize; if (labelUnderNode == true) { yLine = y + (1 - lineCount) / (2 * fontSize); } for (var i = 0; i < lineCount; i++) { ctx.fillText(lines[i], x, yLine); yLine += fontSize; } } }; Node.prototype.getTextSize = function(ctx) { if (this.label !== undefined) { ctx.font = (this.selected ? "bold " : "") + this.options.fontSize + "px " + this.options.fontFace; var lines = this.label.split('\n'), height = (Number(this.options.fontSize) + 4) * lines.length, width = 0; for (var i = 0, iMax = lines.length; i < iMax; i++) { width = Math.max(width, ctx.measureText(lines[i]).width); } return {"width": width, "height": height}; } else { return {"width": 0, "height": 0}; } }; /** * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn. * there is a safety margin of 0.3 * width; * * @returns {boolean} */ Node.prototype.inArea = function() { if (this.width !== undefined) { return (this.x + this.width *this.networkScaleInv >= this.canvasTopLeft.x && this.x - this.width *this.networkScaleInv < this.canvasBottomRight.x && this.y + this.height*this.networkScaleInv >= this.canvasTopLeft.y && this.y - this.height*this.networkScaleInv < this.canvasBottomRight.y); } else { return true; } }; /** * checks if the core of the node is in the display area, this is used for opening clusters around zoom * @returns {boolean} */ Node.prototype.inView = function() { return (this.x >= this.canvasTopLeft.x && this.x < this.canvasBottomRight.x && this.y >= this.canvasTopLeft.y && this.y < this.canvasBottomRight.y); }; /** * This allows the zoom level of the network to influence the rendering * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas * * @param scale * @param canvasTopLeft * @param canvasBottomRight */ Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) { this.networkScaleInv = 1.0/scale; this.networkScale = scale; this.canvasTopLeft = canvasTopLeft; this.canvasBottomRight = canvasBottomRight; }; /** * This allows the zoom level of the network to influence the rendering * * @param scale */ Node.prototype.setScale = function(scale) { this.networkScaleInv = 1.0/scale; this.networkScale = scale; }; /** * set the velocity at 0. Is called when this node is contained in another during clustering */ Node.prototype.clearVelocity = function() { this.vx = 0; this.vy = 0; }; /** * Basic preservation of (kinectic) energy * * @param massBeforeClustering */ Node.prototype.updateVelocity = function(massBeforeClustering) { var energyBefore = this.vx * this.vx * massBeforeClustering; //this.vx = (this.vx < 0) ? -Math.sqrt(energyBefore/this.options.mass) : Math.sqrt(energyBefore/this.options.mass); this.vx = Math.sqrt(energyBefore/this.options.mass); energyBefore = this.vy * this.vy * massBeforeClustering; //this.vy = (this.vy < 0) ? -Math.sqrt(energyBefore/this.options.mass) : Math.sqrt(energyBefore/this.options.mass); this.vy = Math.sqrt(energyBefore/this.options.mass); }; module.exports = Node; /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { /** * Popup is a class to create a popup window with some text * @param {Element} container The container object. * @param {Number} [x] * @param {Number} [y] * @param {String} [text] * @param {Object} [style] An object containing borderColor, * backgroundColor, etc. */ function Popup(container, x, y, text, style) { if (container) { this.container = container; } else { this.container = document.body; } // x, y and text are optional, see if a style object was passed in their place if (style === undefined) { if (typeof x === "object") { style = x; x = undefined; } else if (typeof text === "object") { style = text; text = undefined; } else { // for backwards compatibility, in case clients other than Network are creating Popup directly style = { fontColor: 'black', fontSize: 14, // px fontFace: 'verdana', color: { border: '#666', background: '#FFFFC6' } } } } this.x = 0; this.y = 0; this.padding = 5; if (x !== undefined && y !== undefined ) { this.setPosition(x, y); } if (text !== undefined) { this.setText(text); } // create the frame this.frame = document.createElement("div"); var styleAttr = this.frame.style; styleAttr.position = "absolute"; styleAttr.visibility = "hidden"; styleAttr.border = "1px solid " + style.color.border; styleAttr.color = style.fontColor; styleAttr.fontSize = style.fontSize + "px"; styleAttr.fontFamily = style.fontFace; styleAttr.padding = this.padding + "px"; styleAttr.backgroundColor = style.color.background; styleAttr.borderRadius = "3px"; styleAttr.MozBorderRadius = "3px"; styleAttr.WebkitBorderRadius = "3px"; styleAttr.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)"; styleAttr.whiteSpace = "nowrap"; this.container.appendChild(this.frame); } /** * @param {number} x Horizontal position of the popup window * @param {number} y Vertical position of the popup window */ Popup.prototype.setPosition = function(x, y) { this.x = parseInt(x); this.y = parseInt(y); }; /** * Set the text for the popup window. This can be HTML code * @param {string} text */ Popup.prototype.setText = function(text) { this.frame.innerHTML = text; }; /** * Show the popup window * @param {boolean} show Optional. Show or hide the window */ Popup.prototype.show = function (show) { if (show === undefined) { show = true; } if (show) { var height = this.frame.clientHeight; var width = this.frame.clientWidth; var maxHeight = this.frame.parentNode.clientHeight; var maxWidth = this.frame.parentNode.clientWidth; var top = (this.y - height); if (top + height + this.padding > maxHeight) { top = maxHeight - height - this.padding; } if (top < this.padding) { top = this.padding; } var left = this.x; if (left + width + this.padding > maxWidth) { left = maxWidth - width - this.padding; } if (left < this.padding) { left = this.padding; } this.frame.style.left = left + "px"; this.frame.style.top = top + "px"; this.frame.style.visibility = "visible"; } else { this.hide(); } }; /** * Hide the popup window */ Popup.prototype.hide = function () { this.frame.style.visibility = "hidden"; }; module.exports = Popup; /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { /** * Parse a text source containing data in DOT language into a JSON object. * The object contains two lists: one with nodes and one with edges. * * DOT language reference: http://www.graphviz.org/doc/info/lang.html * * @param {String} data Text containing a graph in DOT-notation * @return {Object} graph An object containing two parameters: * {Object[]} nodes * {Object[]} edges */ function parseDOT (data) { dot = data; return parseGraph(); } // token types enumeration var TOKENTYPE = { NULL : 0, DELIMITER : 1, IDENTIFIER: 2, UNKNOWN : 3 }; // map with all delimiters var DELIMITERS = { '{': true, '}': true, '[': true, ']': true, ';': true, '=': true, ',': true, '->': true, '--': true }; var dot = ''; // current dot file var index = 0; // current index in dot file var c = ''; // current token character in expr var token = ''; // current token var tokenType = TOKENTYPE.NULL; // type of the token /** * Get the first character from the dot file. * The character is stored into the char c. If the end of the dot file is * reached, the function puts an empty string in c. */ function first() { index = 0; c = dot.charAt(0); } /** * Get the next character from the dot file. * The character is stored into the char c. If the end of the dot file is * reached, the function puts an empty string in c. */ function next() { index++; c = dot.charAt(index); } /** * Preview the next character from the dot file. * @return {String} cNext */ function nextPreview() { return dot.charAt(index + 1); } /** * Test whether given character is alphabetic or numeric * @param {String} c * @return {Boolean} isAlphaNumeric */ var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/; function isAlphaNumeric(c) { return regexAlphaNumeric.test(c); } /** * Merge all properties of object b into object b * @param {Object} a * @param {Object} b * @return {Object} a */ function merge (a, b) { if (!a) { a = {}; } if (b) { for (var name in b) { if (b.hasOwnProperty(name)) { a[name] = b[name]; } } } return a; } /** * Set a value in an object, where the provided parameter name can be a * path with nested parameters. For example: * * var obj = {a: 2}; * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}} * * @param {Object} obj * @param {String} path A parameter name or dot-separated parameter path, * like "color.highlight.border". * @param {*} value */ function setValue(obj, path, value) { var keys = path.split('.'); var o = obj; while (keys.length) { var key = keys.shift(); if (keys.length) { // this isn't the end point if (!o[key]) { o[key] = {}; } o = o[key]; } else { // this is the end point o[key] = value; } } } /** * Add a node to a graph object. If there is already a node with * the same id, their attributes will be merged. * @param {Object} graph * @param {Object} node */ function addNode(graph, node) { var i, len; var current = null; // find root graph (in case of subgraph) var graphs = [graph]; // list with all graphs from current graph to root graph var root = graph; while (root.parent) { graphs.push(root.parent); root = root.parent; } // find existing node (at root level) by its id if (root.nodes) { for (i = 0, len = root.nodes.length; i < len; i++) { if (node.id === root.nodes[i].id) { current = root.nodes[i]; break; } } } if (!current) { // this is a new node current = { id: node.id }; if (graph.node) { // clone default attributes current.attr = merge(current.attr, graph.node); } } // add node to this (sub)graph and all its parent graphs for (i = graphs.length - 1; i >= 0; i--) { var g = graphs[i]; if (!g.nodes) { g.nodes = []; } if (g.nodes.indexOf(current) == -1) { g.nodes.push(current); } } // merge attributes if (node.attr) { current.attr = merge(current.attr, node.attr); } } /** * Add an edge to a graph object * @param {Object} graph * @param {Object} edge */ function addEdge(graph, edge) { if (!graph.edges) { graph.edges = []; } graph.edges.push(edge); if (graph.edge) { var attr = merge({}, graph.edge); // clone default attributes edge.attr = merge(attr, edge.attr); // merge attributes } } /** * Create an edge to a graph object * @param {Object} graph * @param {String | Number | Object} from * @param {String | Number | Object} to * @param {String} type * @param {Object | null} attr * @return {Object} edge */ function createEdge(graph, from, to, type, attr) { var edge = { from: from, to: to, type: type }; if (graph.edge) { edge.attr = merge({}, graph.edge); // clone default attributes } edge.attr = merge(edge.attr || {}, attr); // merge attributes return edge; } /** * Get next token in the current dot file. * The token and token type are available as token and tokenType */ function getToken() { tokenType = TOKENTYPE.NULL; token = ''; // skip over whitespaces while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter next(); } do { var isComment = false; // skip comment if (c == '#') { // find the previous non-space character var i = index - 1; while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') { i--; } if (dot.charAt(i) == '\n' || dot.charAt(i) == '') { // the # is at the start of a line, this is indeed a line comment while (c != '' && c != '\n') { next(); } isComment = true; } } if (c == '/' && nextPreview() == '/') { // skip line comment while (c != '' && c != '\n') { next(); } isComment = true; } if (c == '/' && nextPreview() == '*') { // skip block comment while (c != '') { if (c == '*' && nextPreview() == '/') { // end of block comment found. skip these last two characters next(); next(); break; } else { next(); } } isComment = true; } // skip over whitespaces while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter next(); } } while (isComment); // check for end of dot file if (c == '') { // token is still empty tokenType = TOKENTYPE.DELIMITER; return; } // check for delimiters consisting of 2 characters var c2 = c + nextPreview(); if (DELIMITERS[c2]) { tokenType = TOKENTYPE.DELIMITER; token = c2; next(); next(); return; } // check for delimiters consisting of 1 character if (DELIMITERS[c]) { tokenType = TOKENTYPE.DELIMITER; token = c; next(); return; } // check for an identifier (number or string) // TODO: more precise parsing of numbers/strings (and the port separator ':') if (isAlphaNumeric(c) || c == '-') { token += c; next(); while (isAlphaNumeric(c)) { token += c; next(); } if (token == 'false') { token = false; // convert to boolean } else if (token == 'true') { token = true; // convert to boolean } else if (!isNaN(Number(token))) { token = Number(token); // convert to number } tokenType = TOKENTYPE.IDENTIFIER; return; } // check for a string enclosed by double quotes if (c == '"') { next(); while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) { token += c; if (c == '"') { // skip the escape character next(); } next(); } if (c != '"') { throw newSyntaxError('End of string " expected'); } next(); tokenType = TOKENTYPE.IDENTIFIER; return; } // something unknown is found, wrong characters, a syntax error tokenType = TOKENTYPE.UNKNOWN; while (c != '') { token += c; next(); } throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"'); } /** * Parse a graph. * @returns {Object} graph */ function parseGraph() { var graph = {}; first(); getToken(); // optional strict keyword if (token == 'strict') { graph.strict = true; getToken(); } // graph or digraph keyword if (token == 'graph' || token == 'digraph') { graph.type = token; getToken(); } // optional graph id if (tokenType == TOKENTYPE.IDENTIFIER) { graph.id = token; getToken(); } // open angle bracket if (token != '{') { throw newSyntaxError('Angle bracket { expected'); } getToken(); // statements parseStatements(graph); // close angle bracket if (token != '}') { throw newSyntaxError('Angle bracket } expected'); } getToken(); // end of file if (token !== '') { throw newSyntaxError('End of file expected'); } getToken(); // remove temporary default properties delete graph.node; delete graph.edge; delete graph.graph; return graph; } /** * Parse a list with statements. * @param {Object} graph */ function parseStatements (graph) { while (token !== '' && token != '}') { parseStatement(graph); if (token == ';') { getToken(); } } } /** * Parse a single statement. Can be a an attribute statement, node * statement, a series of node statements and edge statements, or a * parameter. * @param {Object} graph */ function parseStatement(graph) { // parse subgraph var subgraph = parseSubgraph(graph); if (subgraph) { // edge statements parseEdge(graph, subgraph); return; } // parse an attribute statement var attr = parseAttributeStatement(graph); if (attr) { return; } // parse node if (tokenType != TOKENTYPE.IDENTIFIER) { throw newSyntaxError('Identifier expected'); } var id = token; // id can be a string or a number getToken(); if (token == '=') { // id statement getToken(); if (tokenType != TOKENTYPE.IDENTIFIER) { throw newSyntaxError('Identifier expected'); } graph[id] = token; getToken(); // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] " } else { parseNodeStatement(graph, id); } } /** * Parse a subgraph * @param {Object} graph parent graph object * @return {Object | null} subgraph */ function parseSubgraph (graph) { var subgraph = null; // optional subgraph keyword if (token == 'subgraph') { subgraph = {}; subgraph.type = 'subgraph'; getToken(); // optional graph id if (tokenType == TOKENTYPE.IDENTIFIER) { subgraph.id = token; getToken(); } } // open angle bracket if (token == '{') { getToken(); if (!subgraph) { subgraph = {}; } subgraph.parent = graph; subgraph.node = graph.node; subgraph.edge = graph.edge; subgraph.graph = graph.graph; // statements parseStatements(subgraph); // close angle bracket if (token != '}') { throw newSyntaxError('Angle bracket } expected'); } getToken(); // remove temporary default properties delete subgraph.node; delete subgraph.edge; delete subgraph.graph; delete subgraph.parent; // register at the parent graph if (!graph.subgraphs) { graph.subgraphs = []; } graph.subgraphs.push(subgraph); } return subgraph; } /** * parse an attribute statement like "node [shape=circle fontSize=16]". * Available keywords are 'node', 'edge', 'graph'. * The previous list with default attributes will be replaced * @param {Object} graph * @returns {String | null} keyword Returns the name of the parsed attribute * (node, edge, graph), or null if nothing * is parsed. */ function parseAttributeStatement (graph) { // attribute statements if (token == 'node') { getToken(); // node attributes graph.node = parseAttributeList(); return 'node'; } else if (token == 'edge') { getToken(); // edge attributes graph.edge = parseAttributeList(); return 'edge'; } else if (token == 'graph') { getToken(); // graph attributes graph.graph = parseAttributeList(); return 'graph'; } return null; } /** * parse a node statement * @param {Object} graph * @param {String | Number} id */ function parseNodeStatement(graph, id) { // node statement var node = { id: id }; var attr = parseAttributeList(); if (attr) { node.attr = attr; } addNode(graph, node); // edge statements parseEdge(graph, id); } /** * Parse an edge or a series of edges * @param {Object} graph * @param {String | Number} from Id of the from node */ function parseEdge(graph, from) { while (token == '->' || token == '--') { var to; var type = token; getToken(); var subgraph = parseSubgraph(graph); if (subgraph) { to = subgraph; } else { if (tokenType != TOKENTYPE.IDENTIFIER) { throw newSyntaxError('Identifier or subgraph expected'); } to = token; addNode(graph, { id: to }); getToken(); } // parse edge attributes var attr = parseAttributeList(); // create edge var edge = createEdge(graph, from, to, type, attr); addEdge(graph, edge); from = to; } } /** * Parse a set with attributes, * for example [label="1.000", shape=solid] * @return {Object | null} attr */ function parseAttributeList() { var attr = null; while (token == '[') { getToken(); attr = {}; while (token !== '' && token != ']') { if (tokenType != TOKENTYPE.IDENTIFIER) { throw newSyntaxError('Attribute name expected'); } var name = token; getToken(); if (token != '=') { throw newSyntaxError('Equal sign = expected'); } getToken(); if (tokenType != TOKENTYPE.IDENTIFIER) { throw newSyntaxError('Attribute value expected'); } var value = token; setValue(attr, name, value); // name can be a path getToken(); if (token ==',') { getToken(); } } if (token != ']') { throw newSyntaxError('Bracket ] expected'); } getToken(); } return attr; } /** * Create a syntax error with extra information on current token and index. * @param {String} message * @returns {SyntaxError} err */ function newSyntaxError(message) { return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')'); } /** * Chop off text after a maximum length * @param {String} text * @param {Number} maxLength * @returns {String} */ function chop (text, maxLength) { return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...'); } /** * Execute a function fn for each pair of elements in two arrays * @param {Array | *} array1 * @param {Array | *} array2 * @param {function} fn */ function forEach2(array1, array2, fn) { if (array1 instanceof Array) { array1.forEach(function (elem1) { if (array2 instanceof Array) { array2.forEach(function (elem2) { fn(elem1, elem2); }); } else { fn(elem1, array2); } }); } else { if (array2 instanceof Array) { array2.forEach(function (elem2) { fn(array1, elem2); }); } else { fn(array1, array2); } } } /** * Convert a string containing a graph in DOT language into a map containing * with nodes and edges in the format of graph. * @param {String} data Text containing a graph in DOT-notation * @return {Object} graphData */ function DOTToGraph (data) { // parse the DOT file var dotData = parseDOT(data); var graphData = { nodes: [], edges: [], options: {} }; // copy the nodes if (dotData.nodes) { dotData.nodes.forEach(function (dotNode) { var graphNode = { id: dotNode.id, label: String(dotNode.label || dotNode.id) }; merge(graphNode, dotNode.attr); if (graphNode.image) { graphNode.shape = 'image'; } graphData.nodes.push(graphNode); }); } // copy the edges if (dotData.edges) { /** * Convert an edge in DOT format to an edge with VisGraph format * @param {Object} dotEdge * @returns {Object} graphEdge */ function convertEdge(dotEdge) { var graphEdge = { from: dotEdge.from, to: dotEdge.to }; merge(graphEdge, dotEdge.attr); graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line'; return graphEdge; } dotData.edges.forEach(function (dotEdge) { var from, to; if (dotEdge.from instanceof Object) { from = dotEdge.from.nodes; } else { from = { id: dotEdge.from } } if (dotEdge.to instanceof Object) { to = dotEdge.to.nodes; } else { to = { id: dotEdge.to } } if (dotEdge.from instanceof Object && dotEdge.from.edges) { dotEdge.from.edges.forEach(function (subEdge) { var graphEdge = convertEdge(subEdge); graphData.edges.push(graphEdge); }); } forEach2(from, to, function (from, to) { var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr); var graphEdge = convertEdge(subEdge); graphData.edges.push(graphEdge); }); if (dotEdge.to instanceof Object && dotEdge.to.edges) { dotEdge.to.edges.forEach(function (subEdge) { var graphEdge = convertEdge(subEdge); graphData.edges.push(graphEdge); }); } }); } // copy the options if (dotData.attr) { graphData.options = dotData.attr; } return graphData; } // exports exports.parseDOT = parseDOT; exports.DOTToGraph = DOTToGraph; /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { function parseGephi(gephiJSON, options) { var edges = []; var nodes = []; this.options = { edges: { inheritColor: true }, nodes: { allowedToMove: false, parseColor: false } }; if (options !== undefined) { this.options.nodes['allowedToMove'] = options.allowedToMove | false; this.options.nodes['parseColor'] = options.parseColor | false; this.options.edges['inheritColor'] = options.inheritColor | true; } var gEdges = gephiJSON.edges; var gNodes = gephiJSON.nodes; for (var i = 0; i < gEdges.length; i++) { var edge = {}; var gEdge = gEdges[i]; edge['id'] = gEdge.id; edge['from'] = gEdge.source; edge['to'] = gEdge.target; edge['attributes'] = gEdge.attributes; // edge['value'] = gEdge.attributes !== undefined ? gEdge.attributes.Weight : undefined; // edge['width'] = edge['value'] !== undefined ? undefined : edgegEdge.size; edge['color'] = gEdge.color; edge['inheritColor'] = edge['color'] !== undefined ? false : this.options.inheritColor; edges.push(edge); } for (var i = 0; i < gNodes.length; i++) { var node = {}; var gNode = gNodes[i]; node['id'] = gNode.id; node['attributes'] = gNode.attributes; node['x'] = gNode.x; node['y'] = gNode.y; node['label'] = gNode.label; if (this.options.nodes.parseColor == true) { node['color'] = gNode.color; } else { node['color'] = gNode.color !== undefined ? {background:gNode.color, border:gNode.color} : undefined; } node['radius'] = gNode.size; node['allowedToMoveX'] = this.options.nodes.allowedToMove; node['allowedToMoveY'] = this.options.nodes.allowedToMove; nodes.push(node); } return {nodes:nodes, edges:edges}; } exports.parseGephi = parseGephi; /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { // first check if moment.js is already loaded in the browser window, if so, // use this instance. Else, load via commonjs. module.exports = (typeof window !== 'undefined') && window['moment'] || __webpack_require__(48); /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { // Only load hammer.js when in a browser environment // (loading hammer.js in a node.js environment gives errors) if (typeof window !== 'undefined') { module.exports = window['Hammer'] || __webpack_require__(49); } else { module.exports = function () { throw Error('hammer.js is only available in a browser, not in node.js.'); } } /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { var Emitter = __webpack_require__(46); var Hammer = __webpack_require__(41); var util = __webpack_require__(1); var DataSet = __webpack_require__(3); var DataView = __webpack_require__(4); var Range = __webpack_require__(15); var TimeAxis = __webpack_require__(27); var CurrentTime = __webpack_require__(19); var CustomTime = __webpack_require__(20); var ItemSet = __webpack_require__(24); /** * Create a timeline visualization * @param {HTMLElement} container * @param {vis.DataSet | Array | google.visualization.DataTable} [items] * @param {Object} [options] See Core.setOptions for the available options. * @constructor */ function Core () {} // turn Core into an event emitter Emitter(Core.prototype); /** * Create the main DOM for the Core: a root panel containing left, right, * top, bottom, content, and background panel. * @param {Element} container The container element where the Core will * be attached. * @private */ Core.prototype._create = function (container) { this.dom = {}; this.dom.root = document.createElement('div'); this.dom.background = document.createElement('div'); this.dom.backgroundVertical = document.createElement('div'); this.dom.backgroundHorizontal = document.createElement('div'); this.dom.centerContainer = document.createElement('div'); this.dom.leftContainer = document.createElement('div'); this.dom.rightContainer = document.createElement('div'); this.dom.center = document.createElement('div'); this.dom.left = document.createElement('div'); this.dom.right = document.createElement('div'); this.dom.top = document.createElement('div'); this.dom.bottom = document.createElement('div'); this.dom.shadowTop = document.createElement('div'); this.dom.shadowBottom = document.createElement('div'); this.dom.shadowTopLeft = document.createElement('div'); this.dom.shadowBottomLeft = document.createElement('div'); this.dom.shadowTopRight = document.createElement('div'); this.dom.shadowBottomRight = document.createElement('div'); this.dom.background.className = 'vispanel background'; this.dom.backgroundVertical.className = 'vispanel background vertical'; this.dom.backgroundHorizontal.className = 'vispanel background horizontal'; this.dom.centerContainer.className = 'vispanel center'; this.dom.leftContainer.className = 'vispanel left'; this.dom.rightContainer.className = 'vispanel right'; this.dom.top.className = 'vispanel top'; this.dom.bottom.className = 'vispanel bottom'; this.dom.left.className = 'content'; this.dom.center.className = 'content'; this.dom.right.className = 'content'; this.dom.shadowTop.className = 'shadow top'; this.dom.shadowBottom.className = 'shadow bottom'; this.dom.shadowTopLeft.className = 'shadow top'; this.dom.shadowBottomLeft.className = 'shadow bottom'; this.dom.shadowTopRight.className = 'shadow top'; this.dom.shadowBottomRight.className = 'shadow bottom'; this.dom.root.appendChild(this.dom.background); this.dom.root.appendChild(this.dom.backgroundVertical); this.dom.root.appendChild(this.dom.backgroundHorizontal); this.dom.root.appendChild(this.dom.centerContainer); this.dom.root.appendChild(this.dom.leftContainer); this.dom.root.appendChild(this.dom.rightContainer); this.dom.root.appendChild(this.dom.top); this.dom.root.appendChild(this.dom.bottom); this.dom.centerContainer.appendChild(this.dom.center); this.dom.leftContainer.appendChild(this.dom.left); this.dom.rightContainer.appendChild(this.dom.right); this.dom.centerContainer.appendChild(this.dom.shadowTop); this.dom.centerContainer.appendChild(this.dom.shadowBottom); this.dom.leftContainer.appendChild(this.dom.shadowTopLeft); this.dom.leftContainer.appendChild(this.dom.shadowBottomLeft); this.dom.rightContainer.appendChild(this.dom.shadowTopRight); this.dom.rightContainer.appendChild(this.dom.shadowBottomRight); this.on('rangechange', this.redraw.bind(this)); this.on('change', this.redraw.bind(this)); this.on('touch', this._onTouch.bind(this)); this.on('pinch', this._onPinch.bind(this)); this.on('dragstart', this._onDragStart.bind(this)); this.on('drag', this._onDrag.bind(this)); // create event listeners for all interesting events, these events will be // emitted via emitter this.hammer = Hammer(this.dom.root, { prevent_default: true }); this.listeners = {}; var me = this; var events = [ 'touch', 'pinch', 'tap', 'doubletap', 'hold', 'dragstart', 'drag', 'dragend', 'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is needed for Firefox ]; events.forEach(function (event) { var listener = function () { var args = [event].concat(Array.prototype.slice.call(arguments, 0)); me.emit.apply(me, args); }; me.hammer.on(event, listener); me.listeners[event] = listener; }); // size properties of each of the panels this.props = { root: {}, background: {}, centerContainer: {}, leftContainer: {}, rightContainer: {}, center: {}, left: {}, right: {}, top: {}, bottom: {}, border: {}, scrollTop: 0, scrollTopMin: 0 }; this.touch = {}; // store state information needed for touch events // attach the root panel to the provided container if (!container) throw new Error('No container provided'); container.appendChild(this.dom.root); }; /** * Destroy the Core, clean up all DOM elements and event listeners. */ Core.prototype.destroy = function () { // unbind datasets this.clear(); // remove all event listeners this.off(); // stop checking for changed size this._stopAutoResize(); // remove from DOM if (this.dom.root.parentNode) { this.dom.root.parentNode.removeChild(this.dom.root); } this.dom = null; // cleanup hammer touch events for (var event in this.listeners) { if (this.listeners.hasOwnProperty(event)) { delete this.listeners[event]; } } this.listeners = null; this.hammer = null; // give all components the opportunity to cleanup this.components.forEach(function (component) { component.destroy(); }); this.body = null; }; /** * Set a custom time bar * @param {Date} time */ Core.prototype.setCustomTime = function (time) { if (!this.customTime) { throw new Error('Cannot get custom time: Custom time bar is not enabled'); } this.customTime.setCustomTime(time); }; /** * Retrieve the current custom time. * @return {Date} customTime */ Core.prototype.getCustomTime = function() { if (!this.customTime) { throw new Error('Cannot get custom time: Custom time bar is not enabled'); } return this.customTime.getCustomTime(); }; /** * Get the id's of the currently visible items. * @returns {Array} The ids of the visible items */ Core.prototype.getVisibleItems = function() { return this.itemSet && this.itemSet.getVisibleItems() || []; }; /** * Clear the Core. By Default, items, groups and options are cleared. * Example usage: * * timeline.clear(); // clear items, groups, and options * timeline.clear({options: true}); // clear options only * * @param {Object} [what] Optionally specify what to clear. By default: * {items: true, groups: true, options: true} */ Core.prototype.clear = function(what) { // clear items if (!what || what.items) { this.setItems(null); } // clear groups if (!what || what.groups) { this.setGroups(null); } // clear options of timeline and of each of the components if (!what || what.options) { this.components.forEach(function (component) { component.setOptions(component.defaultOptions); }); this.setOptions(this.defaultOptions); // this will also do a redraw } }; /** * Set Core window such that it fits all items */ Core.prototype.fit = function() { // apply the data range as range var dataRange = this.getItemRange(); // add 5% space on both sides var start = dataRange.min; var end = dataRange.max; if (start != null && end != null) { var interval = (end.valueOf() - start.valueOf()); if (interval <= 0) { // prevent an empty interval interval = 24 * 60 * 60 * 1000; // 1 day } start = new Date(start.valueOf() - interval * 0.05); end = new Date(end.valueOf() + interval * 0.05); } // skip range set if there is no start and end date if (start === null && end === null) { return; } this.range.setRange(start, end); }; /** * Set the visible window. Both parameters are optional, you can change only * start or only end. Syntax: * * TimeLine.setWindow(start, end) * TimeLine.setWindow(range) * * Where start and end can be a Date, number, or string, and range is an * object with properties start and end. * * @param {Date | Number | String | Object} [start] Start date of visible window * @param {Date | Number | String} [end] End date of visible window */ Core.prototype.setWindow = function(start, end) { if (arguments.length == 1) { var range = arguments[0]; this.range.setRange(range.start, range.end); } else { this.range.setRange(start, end); } }; /** * Get the visible window * @return {{start: Date, end: Date}} Visible range */ Core.prototype.getWindow = function() { var range = this.range.getRange(); return { start: new Date(range.start), end: new Date(range.end) }; }; /** * Force a redraw of the Core. Can be useful to manually redraw when * option autoResize=false */ Core.prototype.redraw = function() { var resized = false, options = this.options, props = this.props, dom = this.dom; if (!dom) return; // when destroyed // update class names dom.root.className = 'vis timeline root ' + options.orientation; // update root width and height options dom.root.style.maxHeight = util.option.asSize(options.maxHeight, ''); dom.root.style.minHeight = util.option.asSize(options.minHeight, ''); dom.root.style.width = util.option.asSize(options.width, ''); // calculate border widths props.border.left = (dom.centerContainer.offsetWidth - dom.centerContainer.clientWidth) / 2; props.border.right = props.border.left; props.border.top = (dom.centerContainer.offsetHeight - dom.centerContainer.clientHeight) / 2; props.border.bottom = props.border.top; var borderRootHeight= dom.root.offsetHeight - dom.root.clientHeight; var borderRootWidth = dom.root.offsetWidth - dom.root.clientWidth; // calculate the heights. If any of the side panels is empty, we set the height to // minus the border width, such that the border will be invisible props.center.height = dom.center.offsetHeight; props.left.height = dom.left.offsetHeight; props.right.height = dom.right.offsetHeight; props.top.height = dom.top.clientHeight || -props.border.top; props.bottom.height = dom.bottom.clientHeight || -props.border.bottom; // TODO: compensate borders when any of the panels is empty. // apply auto height // TODO: only calculate autoHeight when needed (else we cause an extra reflow/repaint of the DOM) var contentHeight = Math.max(props.left.height, props.center.height, props.right.height); var autoHeight = props.top.height + contentHeight + props.bottom.height + borderRootHeight + props.border.top + props.border.bottom; dom.root.style.height = util.option.asSize(options.height, autoHeight + 'px'); // calculate heights of the content panels props.root.height = dom.root.offsetHeight; props.background.height = props.root.height - borderRootHeight; var containerHeight = props.root.height - props.top.height - props.bottom.height - borderRootHeight; props.centerContainer.height = containerHeight; props.leftContainer.height = containerHeight; props.rightContainer.height = props.leftContainer.height; // calculate the widths of the panels props.root.width = dom.root.offsetWidth; props.background.width = props.root.width - borderRootWidth; props.left.width = dom.leftContainer.clientWidth || -props.border.left; props.leftContainer.width = props.left.width; props.right.width = dom.rightContainer.clientWidth || -props.border.right; props.rightContainer.width = props.right.width; var centerWidth = props.root.width - props.left.width - props.right.width - borderRootWidth; props.center.width = centerWidth; props.centerContainer.width = centerWidth; props.top.width = centerWidth; props.bottom.width = centerWidth; // resize the panels dom.background.style.height = props.background.height + 'px'; dom.backgroundVertical.style.height = props.background.height + 'px'; dom.backgroundHorizontal.style.height = props.centerContainer.height + 'px'; dom.centerContainer.style.height = props.centerContainer.height + 'px'; dom.leftContainer.style.height = props.leftContainer.height + 'px'; dom.rightContainer.style.height = props.rightContainer.height + 'px'; dom.background.style.width = props.background.width + 'px'; dom.backgroundVertical.style.width = props.centerContainer.width + 'px'; dom.backgroundHorizontal.style.width = props.background.width + 'px'; dom.centerContainer.style.width = props.center.width + 'px'; dom.top.style.width = props.top.width + 'px'; dom.bottom.style.width = props.bottom.width + 'px'; // reposition the panels dom.background.style.left = '0'; dom.background.style.top = '0'; dom.backgroundVertical.style.left = props.left.width + 'px'; dom.backgroundVertical.style.top = '0'; dom.backgroundHorizontal.style.left = '0'; dom.backgroundHorizontal.style.top = props.top.height + 'px'; dom.centerContainer.style.left = props.left.width + 'px'; dom.centerContainer.style.top = props.top.height + 'px'; dom.leftContainer.style.left = '0'; dom.leftContainer.style.top = props.top.height + 'px'; dom.rightContainer.style.left = (props.left.width + props.center.width) + 'px'; dom.rightContainer.style.top = props.top.height + 'px'; dom.top.style.left = props.left.width + 'px'; dom.top.style.top = '0'; dom.bottom.style.left = props.left.width + 'px'; dom.bottom.style.top = (props.top.height + props.centerContainer.height) + 'px'; // update the scrollTop, feasible range for the offset can be changed // when the height of the Core or of the contents of the center changed this._updateScrollTop(); // reposition the scrollable contents var offset = this.props.scrollTop; if (options.orientation == 'bottom') { offset += Math.max(this.props.centerContainer.height - this.props.center.height - this.props.border.top - this.props.border.bottom, 0); } dom.center.style.left = '0'; dom.center.style.top = offset + 'px'; dom.left.style.left = '0'; dom.left.style.top = offset + 'px'; dom.right.style.left = '0'; dom.right.style.top = offset + 'px'; // show shadows when vertical scrolling is available var visibilityTop = this.props.scrollTop == 0 ? 'hidden' : ''; var visibilityBottom = this.props.scrollTop == this.props.scrollTopMin ? 'hidden' : ''; dom.shadowTop.style.visibility = visibilityTop; dom.shadowBottom.style.visibility = visibilityBottom; dom.shadowTopLeft.style.visibility = visibilityTop; dom.shadowBottomLeft.style.visibility = visibilityBottom; dom.shadowTopRight.style.visibility = visibilityTop; dom.shadowBottomRight.style.visibility = visibilityBottom; // redraw all components this.components.forEach(function (component) { resized = component.redraw() || resized; }); if (resized) { // keep repainting until all sizes are settled this.redraw(); } }; // TODO: deprecated since version 1.1.0, remove some day Core.prototype.repaint = function () { throw new Error('Function repaint is deprecated. Use redraw instead.'); }; /** * Convert a position on screen (pixels) to a datetime * @param {int} x Position on the screen in pixels * @return {Date} time The datetime the corresponds with given position x * @private */ // TODO: move this function to Range Core.prototype._toTime = function(x) { var conversion = this.range.conversion(this.props.center.width); return new Date(x / conversion.scale + conversion.offset); }; /** * Convert a position on the global screen (pixels) to a datetime * @param {int} x Position on the screen in pixels * @return {Date} time The datetime the corresponds with given position x * @private */ // TODO: move this function to Range Core.prototype._toGlobalTime = function(x) { var conversion = this.range.conversion(this.props.root.width); return new Date(x / conversion.scale + conversion.offset); }; /** * Convert a datetime (Date object) into a position on the screen * @param {Date} time A date * @return {int} x The position on the screen in pixels which corresponds * with the given date. * @private */ // TODO: move this function to Range Core.prototype._toScreen = function(time) { var conversion = this.range.conversion(this.props.center.width); return (time.valueOf() - conversion.offset) * conversion.scale; }; /** * Convert a datetime (Date object) into a position on the root * This is used to get the pixel density estimate for the screen, not the center panel * @param {Date} time A date * @return {int} x The position on root in pixels which corresponds * with the given date. * @private */ // TODO: move this function to Range Core.prototype._toGlobalScreen = function(time) { var conversion = this.range.conversion(this.props.root.width); return (time.valueOf() - conversion.offset) * conversion.scale; }; /** * Initialize watching when option autoResize is true * @private */ Core.prototype._initAutoResize = function () { if (this.options.autoResize == true) { this._startAutoResize(); } else { this._stopAutoResize(); } }; /** * Watch for changes in the size of the container. On resize, the Panel will * automatically redraw itself. * @private */ Core.prototype._startAutoResize = function () { var me = this; this._stopAutoResize(); this._onResize = function() { if (me.options.autoResize != true) { // stop watching when the option autoResize is changed to false me._stopAutoResize(); return; } if (me.dom.root) { // check whether the frame is resized if ((me.dom.root.clientWidth != me.props.lastWidth) || (me.dom.root.clientHeight != me.props.lastHeight)) { me.props.lastWidth = me.dom.root.clientWidth; me.props.lastHeight = me.dom.root.clientHeight; me.emit('change'); } } }; // add event listener to window resize util.addEventListener(window, 'resize', this._onResize); this.watchTimer = setInterval(this._onResize, 1000); }; /** * Stop watching for a resize of the frame. * @private */ Core.prototype._stopAutoResize = function () { if (this.watchTimer) { clearInterval(this.watchTimer); this.watchTimer = undefined; } // remove event listener on window.resize util.removeEventListener(window, 'resize', this._onResize); this._onResize = null; }; /** * Start moving the timeline vertically * @param {Event} event * @private */ Core.prototype._onTouch = function (event) { this.touch.allowDragging = true; }; /** * Start moving the timeline vertically * @param {Event} event * @private */ Core.prototype._onPinch = function (event) { this.touch.allowDragging = false; }; /** * Start moving the timeline vertically * @param {Event} event * @private */ Core.prototype._onDragStart = function (event) { this.touch.initialScrollTop = this.props.scrollTop; }; /** * Move the timeline vertically * @param {Event} event * @private */ Core.prototype._onDrag = function (event) { // refuse to drag when we where pinching to prevent the timeline make a jump // when releasing the fingers in opposite order from the touch screen if (!this.touch.allowDragging) return; var delta = event.gesture.deltaY; var oldScrollTop = this._getScrollTop(); var newScrollTop = this._setScrollTop(this.touch.initialScrollTop + delta); if (newScrollTop != oldScrollTop) { this.redraw(); // TODO: this causes two redraws when dragging, the other is triggered by rangechange already } }; /** * Apply a scrollTop * @param {Number} scrollTop * @returns {Number} scrollTop Returns the applied scrollTop * @private */ Core.prototype._setScrollTop = function (scrollTop) { this.props.scrollTop = scrollTop; this._updateScrollTop(); return this.props.scrollTop; }; /** * Update the current scrollTop when the height of the containers has been changed * @returns {Number} scrollTop Returns the applied scrollTop * @private */ Core.prototype._updateScrollTop = function () { // recalculate the scrollTopMin var scrollTopMin = Math.min(this.props.centerContainer.height - this.props.center.height, 0); // is negative or zero if (scrollTopMin != this.props.scrollTopMin) { // in case of bottom orientation, change the scrollTop such that the contents // do not move relative to the time axis at the bottom if (this.options.orientation == 'bottom') { this.props.scrollTop += (scrollTopMin - this.props.scrollTopMin); } this.props.scrollTopMin = scrollTopMin; } // limit the scrollTop to the feasible scroll range if (this.props.scrollTop > 0) this.props.scrollTop = 0; if (this.props.scrollTop < scrollTopMin) this.props.scrollTop = scrollTopMin; return this.props.scrollTop; }; /** * Get the current scrollTop * @returns {number} scrollTop * @private */ Core.prototype._getScrollTop = function () { return this.props.scrollTop; }; module.exports = Core; /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { var Hammer = __webpack_require__(41); /** * Fake a hammer.js gesture. Event can be a ScrollEvent or MouseMoveEvent * @param {Element} element * @param {Event} event */ exports.fakeGesture = function(element, event) { var eventType = null; // for hammer.js 1.0.5 // var gesture = Hammer.event.collectEventData(this, eventType, event); // for hammer.js 1.0.6+ var touches = Hammer.event.getTouchList(event, eventType); var gesture = Hammer.event.collectEventData(this, eventType, touches, event); // on IE in standards mode, no touches are recognized by hammer.js, // resulting in NaN values for center.pageX and center.pageY if (isNaN(gesture.center.pageX)) { gesture.center.pageX = event.pageX; } if (isNaN(gesture.center.pageY)) { gesture.center.pageY = event.pageY; } return gesture; }; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { /** * Canvas shapes used by Network */ if (typeof CanvasRenderingContext2D !== 'undefined') { /** * Draw a circle shape */ CanvasRenderingContext2D.prototype.circle = function(x, y, r) { this.beginPath(); this.arc(x, y, r, 0, 2*Math.PI, false); }; /** * Draw a square shape * @param {Number} x horizontal center * @param {Number} y vertical center * @param {Number} r size, width and height of the square */ CanvasRenderingContext2D.prototype.square = function(x, y, r) { this.beginPath(); this.rect(x - r, y - r, r * 2, r * 2); }; /** * Draw a triangle shape * @param {Number} x horizontal center * @param {Number} y vertical center * @param {Number} r radius, half the length of the sides of the triangle */ CanvasRenderingContext2D.prototype.triangle = function(x, y, r) { // http://en.wikipedia.org/wiki/Equilateral_triangle this.beginPath(); var s = r * 2; var s2 = s / 2; var ir = Math.sqrt(3) / 6 * s; // radius of inner circle var h = Math.sqrt(s * s - s2 * s2); // height this.moveTo(x, y - (h - ir)); this.lineTo(x + s2, y + ir); this.lineTo(x - s2, y + ir); this.lineTo(x, y - (h - ir)); this.closePath(); }; /** * Draw a triangle shape in downward orientation * @param {Number} x horizontal center * @param {Number} y vertical center * @param {Number} r radius */ CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) { // http://en.wikipedia.org/wiki/Equilateral_triangle this.beginPath(); var s = r * 2; var s2 = s / 2; var ir = Math.sqrt(3) / 6 * s; // radius of inner circle var h = Math.sqrt(s * s - s2 * s2); // height this.moveTo(x, y + (h - ir)); this.lineTo(x + s2, y - ir); this.lineTo(x - s2, y - ir); this.lineTo(x, y + (h - ir)); this.closePath(); }; /** * Draw a star shape, a star with 5 points * @param {Number} x horizontal center * @param {Number} y vertical center * @param {Number} r radius, half the length of the sides of the triangle */ CanvasRenderingContext2D.prototype.star = function(x, y, r) { // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/ this.beginPath(); for (var n = 0; n < 10; n++) { var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5; this.lineTo( x + radius * Math.sin(n * 2 * Math.PI / 10), y - radius * Math.cos(n * 2 * Math.PI / 10) ); } this.closePath(); }; /** * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas */ CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) { var r2d = Math.PI/180; if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y this.beginPath(); this.moveTo(x+r,y); this.lineTo(x+w-r,y); this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false); this.lineTo(x+w,y+h-r); this.arc(x+w-r,y+h-r,r,0,r2d*90,false); this.lineTo(x+r,y+h); this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false); this.lineTo(x,y+r); this.arc(x+r,y+r,r,r2d*180,r2d*270,false); }; /** * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas */ CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) { var kappa = .5522848, ox = (w / 2) * kappa, // control point offset horizontal oy = (h / 2) * kappa, // control point offset vertical xe = x + w, // x-end ye = y + h, // y-end xm = x + w / 2, // x-middle ym = y + h / 2; // y-middle this.beginPath(); this.moveTo(x, ym); this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); }; /** * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas */ CanvasRenderingContext2D.prototype.database = function(x, y, w, h) { var f = 1/3; var wEllipse = w; var hEllipse = h * f; var kappa = .5522848, ox = (wEllipse / 2) * kappa, // control point offset horizontal oy = (hEllipse / 2) * kappa, // control point offset vertical xe = x + wEllipse, // x-end ye = y + hEllipse, // y-end xm = x + wEllipse / 2, // x-middle ym = y + hEllipse / 2, // y-middle ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse yeb = y + h; // y-end, bottom ellipse this.beginPath(); this.moveTo(xe, ym); this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); this.lineTo(xe, ymb); this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb); this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb); this.lineTo(x, ym); }; /** * Draw an arrow point (no line) */ CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) { // tail var xt = x - length * Math.cos(angle); var yt = y - length * Math.sin(angle); // inner tail // TODO: allow to customize different shapes var xi = x - length * 0.9 * Math.cos(angle); var yi = y - length * 0.9 * Math.sin(angle); // left var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI); var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI); // right var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI); var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI); this.beginPath(); this.moveTo(x, y); this.lineTo(xl, yl); this.lineTo(xi, yi); this.lineTo(xr, yr); this.closePath(); }; /** * Sets up the dashedLine functionality for drawing * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas * @author David Jordan * @date 2012-08-08 */ CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){ if (!dashArray) dashArray=[10,5]; if (dashLength==0) dashLength = 0.001; // Hack for Safari var dashCount = dashArray.length; this.moveTo(x, y); var dx = (x2-x), dy = (y2-y); var slope = dy/dx; var distRemaining = Math.sqrt( dx*dx + dy*dy ); var dashIndex=0, draw=true; while (distRemaining>=0.1){ var dashLength = dashArray[dashIndex++%dashCount]; if (dashLength > distRemaining) dashLength = distRemaining; var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) ); if (dx<0) xStep = -xStep; x += xStep; y += slope*xStep; this[draw ? 'lineTo' : 'moveTo'](x,y); distRemaining -= dashLength; draw = !draw; } }; // TODO: add diamond shape } /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { var PhysicsMixin = __webpack_require__(56); var ClusterMixin = __webpack_require__(50); var SectorsMixin = __webpack_require__(51); var SelectionMixin = __webpack_require__(52); var ManipulationMixin = __webpack_require__(53); var NavigationMixin = __webpack_require__(54); var HierarchicalLayoutMixin = __webpack_require__(55); /** * Load a mixin into the network object * * @param {Object} sourceVariable | this object has to contain functions. * @private */ exports._loadMixin = function (sourceVariable) { for (var mixinFunction in sourceVariable) { if (sourceVariable.hasOwnProperty(mixinFunction)) { this[mixinFunction] = sourceVariable[mixinFunction]; } } }; /** * removes a mixin from the network object. * * @param {Object} sourceVariable | this object has to contain functions. * @private */ exports._clearMixin = function (sourceVariable) { for (var mixinFunction in sourceVariable) { if (sourceVariable.hasOwnProperty(mixinFunction)) { this[mixinFunction] = undefined; } } }; /** * Mixin the physics system and initialize the parameters required. * * @private */ exports._loadPhysicsSystem = function () { this._loadMixin(PhysicsMixin); this._loadSelectedForceSolver(); if (this.constants.configurePhysics == true) { this._loadPhysicsConfiguration(); } }; /** * Mixin the cluster system and initialize the parameters required. * * @private */ exports._loadClusterSystem = function () { this.clusterSession = 0; this.hubThreshold = 5; this._loadMixin(ClusterMixin); }; /** * Mixin the sector system and initialize the parameters required * * @private */ exports._loadSectorSystem = function () { this.sectors = {}; this.activeSector = ["default"]; this.sectors["active"] = {}; this.sectors["active"]["default"] = {"nodes": {}, "edges": {}, "nodeIndices": [], "formationScale": 1.0, "drawingNode": undefined }; this.sectors["frozen"] = {}; this.sectors["support"] = {"nodes": {}, "edges": {}, "nodeIndices": [], "formationScale": 1.0, "drawingNode": undefined }; this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields this._loadMixin(SectorsMixin); }; /** * Mixin the selection system and initialize the parameters required * * @private */ exports._loadSelectionSystem = function () { this.selectionObj = {nodes: {}, edges: {}}; this._loadMixin(SelectionMixin); }; /** * Mixin the navigationUI (User Interface) system and initialize the parameters required * * @private */ exports._loadManipulationSystem = function () { // reset global variables -- these are used by the selection of nodes and edges. this.blockConnectingEdgeSelection = false; this.forceAppendSelection = false; if (this.constants.dataManipulation.enabled == true) { // load the manipulator HTML elements. All styling done in css. if (this.manipulationDiv === undefined) { this.manipulationDiv = document.createElement('div'); this.manipulationDiv.className = 'network-manipulationDiv'; this.manipulationDiv.id = 'network-manipulationDiv'; if (this.editMode == true) { this.manipulationDiv.style.display = "block"; } else { this.manipulationDiv.style.display = "none"; } this.containerElement.insertBefore(this.manipulationDiv, this.frame); } if (this.editModeDiv === undefined) { this.editModeDiv = document.createElement('div'); this.editModeDiv.className = 'network-manipulation-editMode'; this.editModeDiv.id = 'network-manipulation-editMode'; if (this.editMode == true) { this.editModeDiv.style.display = "none"; } else { this.editModeDiv.style.display = "block"; } this.containerElement.insertBefore(this.editModeDiv, this.frame); } if (this.closeDiv === undefined) { this.closeDiv = document.createElement('div'); this.closeDiv.className = 'network-manipulation-closeDiv'; this.closeDiv.id = 'network-manipulation-closeDiv'; this.closeDiv.style.display = this.manipulationDiv.style.display; this.containerElement.insertBefore(this.closeDiv, this.frame); } // load the manipulation functions this._loadMixin(ManipulationMixin); // create the manipulator toolbar this._createManipulatorBar(); } else { if (this.manipulationDiv !== undefined) { // removes all the bindings and overloads this._createManipulatorBar(); // remove the manipulation divs this.containerElement.removeChild(this.manipulationDiv); this.containerElement.removeChild(this.editModeDiv); this.containerElement.removeChild(this.closeDiv); this.manipulationDiv = undefined; this.editModeDiv = undefined; this.closeDiv = undefined; // remove the mixin functions this._clearMixin(ManipulationMixin); } } }; /** * Mixin the navigation (User Interface) system and initialize the parameters required * * @private */ exports._loadNavigationControls = function () { this._loadMixin(NavigationMixin); // the clean function removes the button divs, this is done to remove the bindings. this._cleanNavigation(); if (this.constants.navigation.enabled == true) { this._loadNavigationElements(); } }; /** * Mixin the hierarchical layout system. * * @private */ exports._loadHierarchySystem = function () { this._loadMixin(HierarchicalLayoutMixin); }; /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { /** * Expose `Emitter`. */ module.exports = Emitter; /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks[event] = this._callbacks[event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ var self = this; this._callbacks = this._callbacks || {}; function on() { self.off(event, on); fn.apply(this, arguments); } on.fn = fn; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; // all if (0 == arguments.length) { this._callbacks = {}; return this; } // specific event var callbacks = this._callbacks[event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks[event]; return this; } // remove specific handler var cb; for (var i = 0; i < callbacks.length; i++) { cb = callbacks[i]; if (cb === fn || cb.fn === fn) { callbacks.splice(i, 1); break; } } return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = [].slice.call(arguments, 1) , callbacks = this._callbacks[event]; if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks[event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2012 Craig Campbell * * 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. * * Mousetrap is a simple keyboard shortcut library for Javascript with * no external dependencies * * @version 1.1.2 * @url craig.is/killing/mice */ /** * mapping of special keycodes to their corresponding keys * * everything in this dictionary cannot use keypress events * so it has to be here to map to the correct keycodes for * keyup/keydown events * * @type {Object} */ var _MAP = { 8: 'backspace', 9: 'tab', 13: 'enter', 16: 'shift', 17: 'ctrl', 18: 'alt', 20: 'capslock', 27: 'esc', 32: 'space', 33: 'pageup', 34: 'pagedown', 35: 'end', 36: 'home', 37: 'left', 38: 'up', 39: 'right', 40: 'down', 45: 'ins', 46: 'del', 91: 'meta', 93: 'meta', 224: 'meta' }, /** * mapping for special characters so they can support * * this dictionary is only used incase you want to bind a * keyup or keydown event to one of these keys * * @type {Object} */ _KEYCODE_MAP = { 106: '*', 107: '+', 109: '-', 110: '.', 111 : '/', 186: ';', 187: '=', 188: ',', 189: '-', 190: '.', 191: '/', 192: '`', 219: '[', 220: '\\', 221: ']', 222: '\'' }, /** * this is a mapping of keys that require shift on a US keypad * back to the non shift equivelents * * this is so you can use keyup events with these keys * * note that this will only work reliably on US keyboards * * @type {Object} */ _SHIFT_MAP = { '~': '`', '!': '1', '@': '2', '#': '3', '$': '4', '%': '5', '^': '6', '&': '7', '*': '8', '(': '9', ')': '0', '_': '-', '+': '=', ':': ';', '\"': '\'', '<': ',', '>': '.', '?': '/', '|': '\\' }, /** * this is a list of special strings you can use to map * to modifier keys when you specify your keyboard shortcuts * * @type {Object} */ _SPECIAL_ALIASES = { 'option': 'alt', 'command': 'meta', 'return': 'enter', 'escape': 'esc' }, /** * variable to store the flipped version of _MAP from above * needed to check if we should use keypress or not when no action * is specified * * @type {Object|undefined} */ _REVERSE_MAP, /** * a list of all the callbacks setup via Mousetrap.bind() * * @type {Object} */ _callbacks = {}, /** * direct map of string combinations to callbacks used for trigger() * * @type {Object} */ _direct_map = {}, /** * keeps track of what level each sequence is at since multiple * sequences can start out with the same sequence * * @type {Object} */ _sequence_levels = {}, /** * variable to store the setTimeout call * * @type {null|number} */ _reset_timer, /** * temporary state where we will ignore the next keyup * * @type {boolean|string} */ _ignore_next_keyup = false, /** * are we currently inside of a sequence? * type of action ("keyup" or "keydown" or "keypress") or false * * @type {boolean|string} */ _inside_sequence = false; /** * loop through the f keys, f1 to f19 and add them to the map * programatically */ for (var i = 1; i < 20; ++i) { _MAP[111 + i] = 'f' + i; } /** * loop through to map numbers on the numeric keypad */ for (i = 0; i <= 9; ++i) { _MAP[i + 96] = i; } /** * cross browser add event method * * @param {Element|HTMLDocument} object * @param {string} type * @param {Function} callback * @returns void */ function _addEvent(object, type, callback) { if (object.addEventListener) { return object.addEventListener(type, callback, false); } object.attachEvent('on' + type, callback); } /** * takes the event and returns the key character * * @param {Event} e * @return {string} */ function _characterFromEvent(e) { // for keypress events we should return the character as is if (e.type == 'keypress') { return String.fromCharCode(e.which); } // for non keypress events the special maps are needed if (_MAP[e.which]) { return _MAP[e.which]; } if (_KEYCODE_MAP[e.which]) { return _KEYCODE_MAP[e.which]; } // if it is not in the special map return String.fromCharCode(e.which).toLowerCase(); } /** * should we stop this event before firing off callbacks * * @param {Event} e * @return {boolean} */ function _stop(e) { var element = e.target || e.srcElement, tag_name = element.tagName; // if the element has the class "mousetrap" then no need to stop if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) { return false; } // stop for input, select, and textarea return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true'); } /** * checks if two arrays are equal * * @param {Array} modifiers1 * @param {Array} modifiers2 * @returns {boolean} */ function _modifiersMatch(modifiers1, modifiers2) { return modifiers1.sort().join(',') === modifiers2.sort().join(','); } /** * resets all sequence counters except for the ones passed in * * @param {Object} do_not_reset * @returns void */ function _resetSequences(do_not_reset) { do_not_reset = do_not_reset || {}; var active_sequences = false, key; for (key in _sequence_levels) { if (do_not_reset[key]) { active_sequences = true; continue; } _sequence_levels[key] = 0; } if (!active_sequences) { _inside_sequence = false; } } /** * finds all callbacks that match based on the keycode, modifiers, * and action * * @param {string} character * @param {Array} modifiers * @param {string} action * @param {boolean=} remove - should we remove any matches * @param {string=} combination * @returns {Array} */ function _getMatches(character, modifiers, action, remove, combination) { var i, callback, matches = []; // if there are no events related to this keycode if (!_callbacks[character]) { return []; } // if a modifier key is coming up on its own we should allow it if (action == 'keyup' && _isModifier(character)) { modifiers = [character]; } // loop through all callbacks for the key that was pressed // and see if any of them match for (i = 0; i < _callbacks[character].length; ++i) { callback = _callbacks[character][i]; // if this is a sequence but it is not at the right level // then move onto the next match if (callback.seq && _sequence_levels[callback.seq] != callback.level) { continue; } // if the action we are looking for doesn't match the action we got // then we should keep going if (action != callback.action) { continue; } // if this is a keypress event that means that we need to only // look at the character, otherwise check the modifiers as // well if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) { // remove is used so if you change your mind and call bind a // second time with a new function the first one is overwritten if (remove && callback.combo == combination) { _callbacks[character].splice(i, 1); } matches.push(callback); } } return matches; } /** * takes a key event and figures out what the modifiers are * * @param {Event} e * @returns {Array} */ function _eventModifiers(e) { var modifiers = []; if (e.shiftKey) { modifiers.push('shift'); } if (e.altKey) { modifiers.push('alt'); } if (e.ctrlKey) { modifiers.push('ctrl'); } if (e.metaKey) { modifiers.push('meta'); } return modifiers; } /** * actually calls the callback function * * if your callback function returns false this will use the jquery * convention - prevent default and stop propogation on the event * * @param {Function} callback * @param {Event} e * @returns void */ function _fireCallback(callback, e) { if (callback(e) === false) { if (e.preventDefault) { e.preventDefault(); } if (e.stopPropagation) { e.stopPropagation(); } e.returnValue = false; e.cancelBubble = true; } } /** * handles a character key event * * @param {string} character * @param {Event} e * @returns void */ function _handleCharacter(character, e) { // if this event should not happen stop here if (_stop(e)) { return; } var callbacks = _getMatches(character, _eventModifiers(e), e.type), i, do_not_reset = {}, processed_sequence_callback = false; // loop through matching callbacks for this key event for (i = 0; i < callbacks.length; ++i) { // fire for all sequence callbacks // this is because if for example you have multiple sequences // bound such as "g i" and "g t" they both need to fire the // callback for matching g cause otherwise you can only ever // match the first one if (callbacks[i].seq) { processed_sequence_callback = true; // keep a list of which sequences were matches for later do_not_reset[callbacks[i].seq] = 1; _fireCallback(callbacks[i].callback, e); continue; } // if there were no sequence matches but we are still here // that means this is a regular match so we should fire that if (!processed_sequence_callback && !_inside_sequence) { _fireCallback(callbacks[i].callback, e); } } // if you are inside of a sequence and the key you are pressing // is not a modifier key then we should reset all sequences // that were not matched by this key event if (e.type == _inside_sequence && !_isModifier(character)) { _resetSequences(do_not_reset); } } /** * handles a keydown event * * @param {Event} e * @returns void */ function _handleKey(e) { // normalize e.which for key events // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion e.which = typeof e.which == "number" ? e.which : e.keyCode; var character = _characterFromEvent(e); // no character found then stop if (!character) { return; } if (e.type == 'keyup' && _ignore_next_keyup == character) { _ignore_next_keyup = false; return; } _handleCharacter(character, e); } /** * determines if the keycode specified is a modifier key or not * * @param {string} key * @returns {boolean} */ function _isModifier(key) { return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta'; } /** * called to set a 1 second timeout on the specified sequence * * this is so after each key press in the sequence you have 1 second * to press the next key before you have to start over * * @returns void */ function _resetSequenceTimer() { clearTimeout(_reset_timer); _reset_timer = setTimeout(_resetSequences, 1000); } /** * reverses the map lookup so that we can look for specific keys * to see what can and can't use keypress * * @return {Object} */ function _getReverseMap() { if (!_REVERSE_MAP) { _REVERSE_MAP = {}; for (var key in _MAP) { // pull out the numeric keypad from here cause keypress should // be able to detect the keys from the character if (key > 95 && key < 112) { continue; } if (_MAP.hasOwnProperty(key)) { _REVERSE_MAP[_MAP[key]] = key; } } } return _REVERSE_MAP; } /** * picks the best action based on the key combination * * @param {string} key - character for key * @param {Array} modifiers * @param {string=} action passed in */ function _pickBestAction(key, modifiers, action) { // if no action was picked in we should try to pick the one // that we think would work best for this key if (!action) { action = _getReverseMap()[key] ? 'keydown' : 'keypress'; } // modifier keys don't work as expected with keypress, // switch to keydown if (action == 'keypress' && modifiers.length) { action = 'keydown'; } return action; } /** * binds a key sequence to an event * * @param {string} combo - combo specified in bind call * @param {Array} keys * @param {Function} callback * @param {string=} action * @returns void */ function _bindSequence(combo, keys, callback, action) { // start off by adding a sequence level record for this combination // and setting the level to 0 _sequence_levels[combo] = 0; // if there is no action pick the best one for the first key // in the sequence if (!action) { action = _pickBestAction(keys[0], []); } /** * callback to increase the sequence level for this sequence and reset * all other sequences that were active * * @param {Event} e * @returns void */ var _increaseSequence = function(e) { _inside_sequence = action; ++_sequence_levels[combo]; _resetSequenceTimer(); }, /** * wraps the specified callback inside of another function in order * to reset all sequence counters as soon as this sequence is done * * @param {Event} e * @returns void */ _callbackAndReset = function(e) { _fireCallback(callback, e); // we should ignore the next key up if the action is key down // or keypress. this is so if you finish a sequence and // release the key the final key will not trigger a keyup if (action !== 'keyup') { _ignore_next_keyup = _characterFromEvent(e); } // weird race condition if a sequence ends with the key // another sequence begins with setTimeout(_resetSequences, 10); }, i; // loop through keys one at a time and bind the appropriate callback // function. for any key leading up to the final one it should // increase the sequence. after the final, it should reset all sequences for (i = 0; i < keys.length; ++i) { _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i); } } /** * binds a single keyboard combination * * @param {string} combination * @param {Function} callback * @param {string=} action * @param {string=} sequence_name - name of sequence if part of sequence * @param {number=} level - what part of the sequence the command is * @returns void */ function _bindSingle(combination, callback, action, sequence_name, level) { // make sure multiple spaces in a row become a single space combination = combination.replace(/\s+/g, ' '); var sequence = combination.split(' '), i, key, keys, modifiers = []; // if this pattern is a sequence of keys then run through this method // to reprocess each pattern one key at a time if (sequence.length > 1) { return _bindSequence(combination, sequence, callback, action); } // take the keys from this pattern and figure out what the actual // pattern is all about keys = combination === '+' ? ['+'] : combination.split('+'); for (i = 0; i < keys.length; ++i) { key = keys[i]; // normalize key names if (_SPECIAL_ALIASES[key]) { key = _SPECIAL_ALIASES[key]; } // if this is not a keypress event then we should // be smart about using shift keys // this will only work for US keyboards however if (action && action != 'keypress' && _SHIFT_MAP[key]) { key = _SHIFT_MAP[key]; modifiers.push('shift'); } // if this key is a modifier then add it to the list of modifiers if (_isModifier(key)) { modifiers.push(key); } } // depending on what the key combination is // we will try to pick the best event for it action = _pickBestAction(key, modifiers, action); // make sure to initialize array if this is the first time // a callback is added for this key if (!_callbacks[key]) { _callbacks[key] = []; } // remove an existing match if there is one _getMatches(key, modifiers, action, !sequence_name, combination); // add this call back to the array // if it is a sequence put it at the beginning // if not put it at the end // // this is important because the way these are processed expects // the sequence ones to come first _callbacks[key][sequence_name ? 'unshift' : 'push']({ callback: callback, modifiers: modifiers, action: action, seq: sequence_name, level: level, combo: combination }); } /** * binds multiple combinations to the same callback * * @param {Array} combinations * @param {Function} callback * @param {string|undefined} action * @returns void */ function _bindMultiple(combinations, callback, action) { for (var i = 0; i < combinations.length; ++i) { _bindSingle(combinations[i], callback, action); } } // start! _addEvent(document, 'keypress', _handleKey); _addEvent(document, 'keydown', _handleKey); _addEvent(document, 'keyup', _handleKey); var mousetrap = { /** * binds an event to mousetrap * * can be a single key, a combination of keys separated with +, * a comma separated list of keys, an array of keys, or * a sequence of keys separated by spaces * * be sure to list the modifier keys first to make sure that the * correct key ends up getting bound (the last key in the pattern) * * @param {string|Array} keys * @param {Function} callback * @param {string=} action - 'keypress', 'keydown', or 'keyup' * @returns void */ bind: function(keys, callback, action) { _bindMultiple(keys instanceof Array ? keys : [keys], callback, action); _direct_map[keys + ':' + action] = callback; return this; }, /** * unbinds an event to mousetrap * * the unbinding sets the callback function of the specified key combo * to an empty function and deletes the corresponding key in the * _direct_map dict. * * the keycombo+action has to be exactly the same as * it was defined in the bind method * * TODO: actually remove this from the _callbacks dictionary instead * of binding an empty function * * @param {string|Array} keys * @param {string} action * @returns void */ unbind: function(keys, action) { if (_direct_map[keys + ':' + action]) { delete _direct_map[keys + ':' + action]; this.bind(keys, function() {}, action); } return this; }, /** * triggers an event that has already been bound * * @param {string} keys * @param {string=} action * @returns void */ trigger: function(keys, action) { _direct_map[keys + ':' + action](); return this; }, /** * resets the library back to its initial state. this is useful * if you want to clear out the current keyboard shortcuts and bind * new ones - for example if you switch to another page * * @returns void */ reset: function() { _callbacks = {}; _direct_map = {}; return this; } }; module.exports = mousetrap; /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(global, module) {//! moment.js //! version : 2.8.1 //! authors : Tim Wood, Iskren Chernev, Moment.js contributors //! license : MIT //! momentjs.com (function (undefined) { /************************************ Constants ************************************/ var moment, VERSION = '2.8.1', // the global-scope this is NOT the global object in Node.js globalScope = typeof global !== 'undefined' ? global : this, oldGlobalMoment, round = Math.round, i, YEAR = 0, MONTH = 1, DATE = 2, HOUR = 3, MINUTE = 4, SECOND = 5, MILLISECOND = 6, // internal storage for locale config files locales = {}, // extra moment internal properties (plugins register props here) momentProperties = [], // check for nodeJS hasModule = (typeof module !== 'undefined' && module.exports), // ASP.NET json date format regex aspNetJsonRegex = /^\/?Date\((\-?\d+)/i, aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/, // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/, // format tokens formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|X|zz?|ZZ?|.)/g, localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g, // parsing token regexes parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99 parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999 parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999 parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999 parseTokenDigits = /\d+/, // nonzero number of digits parseTokenWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i, // any word (or two) characters or numbers including two/three word month in arabic. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z parseTokenT = /T/i, // T (ISO separator) parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123 parseTokenOrdinal = /\d{1,2}/, //strict parsing regexes parseTokenOneDigit = /\d/, // 0 - 9 parseTokenTwoDigits = /\d\d/, // 00 - 99 parseTokenThreeDigits = /\d{3}/, // 000 - 999 parseTokenFourDigits = /\d{4}/, // 0000 - 9999 parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999 parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf // iso 8601 regex // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00) isoRegex = /^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/, isoFormat = 'YYYY-MM-DDTHH:mm:ssZ', isoDates = [ ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/], ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/], ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/], ['GGGG-[W]WW', /\d{4}-W\d{2}/], ['YYYY-DDD', /\d{4}-\d{3}/] ], // iso time formats and regexes isoTimes = [ ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/], ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/], ['HH:mm', /(T| )\d\d:\d\d/], ['HH', /(T| )\d\d/] ], // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"] parseTimezoneChunker = /([\+\-]|\d\d)/gi, // getter and setter names proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'), unitMillisecondFactors = { 'Milliseconds' : 1, 'Seconds' : 1e3, 'Minutes' : 6e4, 'Hours' : 36e5, 'Days' : 864e5, 'Months' : 2592e6, 'Years' : 31536e6 }, unitAliases = { ms : 'millisecond', s : 'second', m : 'minute', h : 'hour', d : 'day', D : 'date', w : 'week', W : 'isoWeek', M : 'month', Q : 'quarter', y : 'year', DDD : 'dayOfYear', e : 'weekday', E : 'isoWeekday', gg: 'weekYear', GG: 'isoWeekYear' }, camelFunctions = { dayofyear : 'dayOfYear', isoweekday : 'isoWeekday', isoweek : 'isoWeek', weekyear : 'weekYear', isoweekyear : 'isoWeekYear' }, // format function strings formatFunctions = {}, // default relative time thresholds relativeTimeThresholds = { s: 45, // seconds to minute m: 45, // minutes to hour h: 22, // hours to day d: 26, // days to month M: 11 // months to year }, // tokens to ordinalize and pad ordinalizeTokens = 'DDD w W M D d'.split(' '), paddedTokens = 'M D H h m s w W'.split(' '), formatTokenFunctions = { M : function () { return this.month() + 1; }, MMM : function (format) { return this.localeData().monthsShort(this, format); }, MMMM : function (format) { return this.localeData().months(this, format); }, D : function () { return this.date(); }, DDD : function () { return this.dayOfYear(); }, d : function () { return this.day(); }, dd : function (format) { return this.localeData().weekdaysMin(this, format); }, ddd : function (format) { return this.localeData().weekdaysShort(this, format); }, dddd : function (format) { return this.localeData().weekdays(this, format); }, w : function () { return this.week(); }, W : function () { return this.isoWeek(); }, YY : function () { return leftZeroFill(this.year() % 100, 2); }, YYYY : function () { return leftZeroFill(this.year(), 4); }, YYYYY : function () { return leftZeroFill(this.year(), 5); }, YYYYYY : function () { var y = this.year(), sign = y >= 0 ? '+' : '-'; return sign + leftZeroFill(Math.abs(y), 6); }, gg : function () { return leftZeroFill(this.weekYear() % 100, 2); }, gggg : function () { return leftZeroFill(this.weekYear(), 4); }, ggggg : function () { return leftZeroFill(this.weekYear(), 5); }, GG : function () { return leftZeroFill(this.isoWeekYear() % 100, 2); }, GGGG : function () { return leftZeroFill(this.isoWeekYear(), 4); }, GGGGG : function () { return leftZeroFill(this.isoWeekYear(), 5); }, e : function () { return this.weekday(); }, E : function () { return this.isoWeekday(); }, a : function () { return this.localeData().meridiem(this.hours(), this.minutes(), true); }, A : function () { return this.localeData().meridiem(this.hours(), this.minutes(), false); }, H : function () { return this.hours(); }, h : function () { return this.hours() % 12 || 12; }, m : function () { return this.minutes(); }, s : function () { return this.seconds(); }, S : function () { return toInt(this.milliseconds() / 100); }, SS : function () { return leftZeroFill(toInt(this.milliseconds() / 10), 2); }, SSS : function () { return leftZeroFill(this.milliseconds(), 3); }, SSSS : function () { return leftZeroFill(this.milliseconds(), 3); }, Z : function () { var a = -this.zone(), b = '+'; if (a < 0) { a = -a; b = '-'; } return b + leftZeroFill(toInt(a / 60), 2) + ':' + leftZeroFill(toInt(a) % 60, 2); }, ZZ : function () { var a = -this.zone(), b = '+'; if (a < 0) { a = -a; b = '-'; } return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2); }, z : function () { return this.zoneAbbr(); }, zz : function () { return this.zoneName(); }, X : function () { return this.unix(); }, Q : function () { return this.quarter(); } }, deprecations = {}, lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin']; // Pick the first defined of two or three arguments. dfl comes from // default. function dfl(a, b, c) { switch (arguments.length) { case 2: return a != null ? a : b; case 3: return a != null ? a : b != null ? b : c; default: throw new Error('Implement me'); } } function defaultParsingFlags() { // We need to deep clone this object, and es5 standard is not very // helpful. return { empty : false, unusedTokens : [], unusedInput : [], overflow : -2, charsLeftOver : 0, nullInput : false, invalidMonth : null, invalidFormat : false, userInvalidated : false, iso: false }; } function printMsg(msg) { if (moment.suppressDeprecationWarnings === false && typeof console !== 'undefined' && console.warn) { console.warn("Deprecation warning: " + msg); } } function deprecate(msg, fn) { var firstTime = true; return extend(function () { if (firstTime) { printMsg(msg); firstTime = false; } return fn.apply(this, arguments); }, fn); } function deprecateSimple(name, msg) { if (!deprecations[name]) { printMsg(msg); deprecations[name] = true; } } function padToken(func, count) { return function (a) { return leftZeroFill(func.call(this, a), count); }; } function ordinalizeToken(func, period) { return function (a) { return this.localeData().ordinal(func.call(this, a), period); }; } while (ordinalizeTokens.length) { i = ordinalizeTokens.pop(); formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i); } while (paddedTokens.length) { i = paddedTokens.pop(); formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2); } formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3); /************************************ Constructors ************************************/ function Locale() { } // Moment prototype object function Moment(config, skipOverflow) { if (skipOverflow !== false) { checkOverflow(config); } copyConfig(this, config); this._d = new Date(+config._d); } // Duration Constructor function Duration(duration) { var normalizedInput = normalizeObjectUnits(duration), years = normalizedInput.year || 0, quarters = normalizedInput.quarter || 0, months = normalizedInput.month || 0, weeks = normalizedInput.week || 0, days = normalizedInput.day || 0, hours = normalizedInput.hour || 0, minutes = normalizedInput.minute || 0, seconds = normalizedInput.second || 0, milliseconds = normalizedInput.millisecond || 0; // representation for dateAddRemove this._milliseconds = +milliseconds + seconds * 1e3 + // 1000 minutes * 6e4 + // 1000 * 60 hours * 36e5; // 1000 * 60 * 60 // Because of dateAddRemove treats 24 hours as different from a // day when working around DST, we need to store them separately this._days = +days + weeks * 7; // It is impossible translate months into days without knowing // which months you are are talking about, so we have to store // it separately. this._months = +months + quarters * 3 + years * 12; this._data = {}; this._locale = moment.localeData(); this._bubble(); } /************************************ Helpers ************************************/ function extend(a, b) { for (var i in b) { if (b.hasOwnProperty(i)) { a[i] = b[i]; } } if (b.hasOwnProperty('toString')) { a.toString = b.toString; } if (b.hasOwnProperty('valueOf')) { a.valueOf = b.valueOf; } return a; } function copyConfig(to, from) { var i, prop, val; if (typeof from._isAMomentObject !== 'undefined') { to._isAMomentObject = from._isAMomentObject; } if (typeof from._i !== 'undefined') { to._i = from._i; } if (typeof from._f !== 'undefined') { to._f = from._f; } if (typeof from._l !== 'undefined') { to._l = from._l; } if (typeof from._strict !== 'undefined') { to._strict = from._strict; } if (typeof from._tzm !== 'undefined') { to._tzm = from._tzm; } if (typeof from._isUTC !== 'undefined') { to._isUTC = from._isUTC; } if (typeof from._offset !== 'undefined') { to._offset = from._offset; } if (typeof from._pf !== 'undefined') { to._pf = from._pf; } if (typeof from._locale !== 'undefined') { to._locale = from._locale; } if (momentProperties.length > 0) { for (i in momentProperties) { prop = momentProperties[i]; val = from[prop]; if (typeof val !== 'undefined') { to[prop] = val; } } } return to; } function absRound(number) { if (number < 0) { return Math.ceil(number); } else { return Math.floor(number); } } // left zero fill a number // see http://jsperf.com/left-zero-filling for performance comparison function leftZeroFill(number, targetLength, forceSign) { var output = '' + Math.abs(number), sign = number >= 0; while (output.length < targetLength) { output = '0' + output; } return (sign ? (forceSign ? '+' : '') : '-') + output; } function positiveMomentsDifference(base, other) { var res = {milliseconds: 0, months: 0}; res.months = other.month() - base.month() + (other.year() - base.year()) * 12; if (base.clone().add(res.months, 'M').isAfter(other)) { --res.months; } res.milliseconds = +other - +(base.clone().add(res.months, 'M')); return res; } function momentsDifference(base, other) { var res; other = makeAs(other, base); if (base.isBefore(other)) { res = positiveMomentsDifference(base, other); } else { res = positiveMomentsDifference(other, base); res.milliseconds = -res.milliseconds; res.months = -res.months; } return res; } // TODO: remove 'name' arg after deprecation is removed function createAdder(direction, name) { return function (val, period) { var dur, tmp; //invert the arguments, but complain about it if (period !== null && !isNaN(+period)) { deprecateSimple(name, "moment()." + name + "(period, number) is deprecated. Please use moment()." + name + "(number, period)."); tmp = val; val = period; period = tmp; } val = typeof val === 'string' ? +val : val; dur = moment.duration(val, period); addOrSubtractDurationFromMoment(this, dur, direction); return this; }; } function addOrSubtractDurationFromMoment(mom, duration, isAdding, updateOffset) { var milliseconds = duration._milliseconds, days = duration._days, months = duration._months; updateOffset = updateOffset == null ? true : updateOffset; if (milliseconds) { mom._d.setTime(+mom._d + milliseconds * isAdding); } if (days) { rawSetter(mom, 'Date', rawGetter(mom, 'Date') + days * isAdding); } if (months) { rawMonthSetter(mom, rawGetter(mom, 'Month') + months * isAdding); } if (updateOffset) { moment.updateOffset(mom, days || months); } } // check if is an array function isArray(input) { return Object.prototype.toString.call(input) === '[object Array]'; } function isDate(input) { return Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date; } // compare two arrays, return the number of differences function compareArrays(array1, array2, dontConvert) { var len = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0, i; for (i = 0; i < len; i++) { if ((dontConvert && array1[i] !== array2[i]) || (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { diffs++; } } return diffs + lengthDiff; } function normalizeUnits(units) { if (units) { var lowered = units.toLowerCase().replace(/(.)s$/, '$1'); units = unitAliases[units] || camelFunctions[lowered] || lowered; } return units; } function normalizeObjectUnits(inputObject) { var normalizedInput = {}, normalizedProp, prop; for (prop in inputObject) { if (inputObject.hasOwnProperty(prop)) { normalizedProp = normalizeUnits(prop); if (normalizedProp) { normalizedInput[normalizedProp] = inputObject[prop]; } } } return normalizedInput; } function makeList(field) { var count, setter; if (field.indexOf('week') === 0) { count = 7; setter = 'day'; } else if (field.indexOf('month') === 0) { count = 12; setter = 'month'; } else { return; } moment[field] = function (format, index) { var i, getter, method = moment._locale[field], results = []; if (typeof format === 'number') { index = format; format = undefined; } getter = function (i) { var m = moment().utc().set(setter, i); return method.call(moment._locale, m, format || ''); }; if (index != null) { return getter(index); } else { for (i = 0; i < count; i++) { results.push(getter(i)); } return results; } }; } function toInt(argumentForCoercion) { var coercedNumber = +argumentForCoercion, value = 0; if (coercedNumber !== 0 && isFinite(coercedNumber)) { if (coercedNumber >= 0) { value = Math.floor(coercedNumber); } else { value = Math.ceil(coercedNumber); } } return value; } function daysInMonth(year, month) { return new Date(Date.UTC(year, month + 1, 0)).getUTCDate(); } function weeksInYear(year, dow, doy) { return weekOfYear(moment([year, 11, 31 + dow - doy]), dow, doy).week; } function daysInYear(year) { return isLeapYear(year) ? 366 : 365; } function isLeapYear(year) { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; } function checkOverflow(m) { var overflow; if (m._a && m._pf.overflow === -2) { overflow = m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH : m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE : m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR : m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE : m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND : m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND : -1; if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { overflow = DATE; } m._pf.overflow = overflow; } } function isValid(m) { if (m._isValid == null) { m._isValid = !isNaN(m._d.getTime()) && m._pf.overflow < 0 && !m._pf.empty && !m._pf.invalidMonth && !m._pf.nullInput && !m._pf.invalidFormat && !m._pf.userInvalidated; if (m._strict) { m._isValid = m._isValid && m._pf.charsLeftOver === 0 && m._pf.unusedTokens.length === 0; } } return m._isValid; } function normalizeLocale(key) { return key ? key.toLowerCase().replace('_', '-') : key; } // pick the locale from the array // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root function chooseLocale(names) { var i = 0, j, next, locale, split; while (i < names.length) { split = normalizeLocale(names[i]).split('-'); j = split.length; next = normalizeLocale(names[i + 1]); next = next ? next.split('-') : null; while (j > 0) { locale = loadLocale(split.slice(0, j).join('-')); if (locale) { return locale; } if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { //the next array item is better than a shallower substring of this one break; } j--; } i++; } return null; } function loadLocale(name) { var oldLocale = null; if (!locales[name] && hasModule) { try { oldLocale = moment.locale(); !(function webpackMissingModule() { var e = new Error("Cannot find module \"./locale\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()); // because defineLocale currently also sets the global locale, we want to undo that for lazy loaded locales moment.locale(oldLocale); } catch (e) { } } return locales[name]; } // Return a moment from input, that is local/utc/zone equivalent to model. function makeAs(input, model) { return model._isUTC ? moment(input).zone(model._offset || 0) : moment(input).local(); } /************************************ Locale ************************************/ extend(Locale.prototype, { set : function (config) { var prop, i; for (i in config) { prop = config[i]; if (typeof prop === 'function') { this[i] = prop; } else { this['_' + i] = prop; } } }, _months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), months : function (m) { return this._months[m.month()]; }, _monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), monthsShort : function (m) { return this._monthsShort[m.month()]; }, monthsParse : function (monthName) { var i, mom, regex; if (!this._monthsParse) { this._monthsParse = []; } for (i = 0; i < 12; i++) { // make the regex if we don't have it already if (!this._monthsParse[i]) { mom = moment.utc([2000, i]); regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (this._monthsParse[i].test(monthName)) { return i; } } }, _weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), weekdays : function (m) { return this._weekdays[m.day()]; }, _weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), weekdaysShort : function (m) { return this._weekdaysShort[m.day()]; }, _weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), weekdaysMin : function (m) { return this._weekdaysMin[m.day()]; }, weekdaysParse : function (weekdayName) { var i, mom, regex; if (!this._weekdaysParse) { this._weekdaysParse = []; } for (i = 0; i < 7; i++) { // make the regex if we don't have it already if (!this._weekdaysParse[i]) { mom = moment([2000, 1]).day(i); regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (this._weekdaysParse[i].test(weekdayName)) { return i; } } }, _longDateFormat : { LT : 'h:mm A', L : 'MM/DD/YYYY', LL : 'MMMM D, YYYY', LLL : 'MMMM D, YYYY LT', LLLL : 'dddd, MMMM D, YYYY LT' }, longDateFormat : function (key) { var output = this._longDateFormat[key]; if (!output && this._longDateFormat[key.toUpperCase()]) { output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) { return val.slice(1); }); this._longDateFormat[key] = output; } return output; }, isPM : function (input) { // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays // Using charAt should be more compatible. return ((input + '').toLowerCase().charAt(0) === 'p'); }, _meridiemParse : /[ap]\.?m?\.?/i, meridiem : function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'pm' : 'PM'; } else { return isLower ? 'am' : 'AM'; } }, _calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, calendar : function (key, mom) { var output = this._calendar[key]; return typeof output === 'function' ? output.apply(mom) : output; }, _relativeTime : { future : 'in %s', past : '%s ago', s : 'a few seconds', m : 'a minute', mm : '%d minutes', h : 'an hour', hh : '%d hours', d : 'a day', dd : '%d days', M : 'a month', MM : '%d months', y : 'a year', yy : '%d years' }, relativeTime : function (number, withoutSuffix, string, isFuture) { var output = this._relativeTime[string]; return (typeof output === 'function') ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number); }, pastFuture : function (diff, output) { var format = this._relativeTime[diff > 0 ? 'future' : 'past']; return typeof format === 'function' ? format(output) : format.replace(/%s/i, output); }, ordinal : function (number) { return this._ordinal.replace('%d', number); }, _ordinal : '%d', preparse : function (string) { return string; }, postformat : function (string) { return string; }, week : function (mom) { return weekOfYear(mom, this._week.dow, this._week.doy).week; }, _week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. }, _invalidDate: 'Invalid date', invalidDate: function () { return this._invalidDate; } }); /************************************ Formatting ************************************/ function removeFormattingTokens(input) { if (input.match(/\[[\s\S]/)) { return input.replace(/^\[|\]$/g, ''); } return input.replace(/\\/g, ''); } function makeFormatFunction(format) { var array = format.match(formattingTokens), i, length; for (i = 0, length = array.length; i < length; i++) { if (formatTokenFunctions[array[i]]) { array[i] = formatTokenFunctions[array[i]]; } else { array[i] = removeFormattingTokens(array[i]); } } return function (mom) { var output = ''; for (i = 0; i < length; i++) { output += array[i] instanceof Function ? array[i].call(mom, format) : array[i]; } return output; }; } // format date using native date object function formatMoment(m, format) { if (!m.isValid()) { return m.localeData().invalidDate(); } format = expandFormat(format, m.localeData()); if (!formatFunctions[format]) { formatFunctions[format] = makeFormatFunction(format); } return formatFunctions[format](m); } function expandFormat(format, locale) { var i = 5; function replaceLongDateFormatTokens(input) { return locale.longDateFormat(input) || input; } localFormattingTokens.lastIndex = 0; while (i >= 0 && localFormattingTokens.test(format)) { format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); localFormattingTokens.lastIndex = 0; i -= 1; } return format; } /************************************ Parsing ************************************/ // get the regex to find the next token function getParseRegexForToken(token, config) { var a, strict = config._strict; switch (token) { case 'Q': return parseTokenOneDigit; case 'DDDD': return parseTokenThreeDigits; case 'YYYY': case 'GGGG': case 'gggg': return strict ? parseTokenFourDigits : parseTokenOneToFourDigits; case 'Y': case 'G': case 'g': return parseTokenSignedNumber; case 'YYYYYY': case 'YYYYY': case 'GGGGG': case 'ggggg': return strict ? parseTokenSixDigits : parseTokenOneToSixDigits; case 'S': if (strict) { return parseTokenOneDigit; } /* falls through */ case 'SS': if (strict) { return parseTokenTwoDigits; } /* falls through */ case 'SSS': if (strict) { return parseTokenThreeDigits; } /* falls through */ case 'DDD': return parseTokenOneToThreeDigits; case 'MMM': case 'MMMM': case 'dd': case 'ddd': case 'dddd': return parseTokenWord; case 'a': case 'A': return config._locale._meridiemParse; case 'X': return parseTokenTimestampMs; case 'Z': case 'ZZ': return parseTokenTimezone; case 'T': return parseTokenT; case 'SSSS': return parseTokenDigits; case 'MM': case 'DD': case 'YY': case 'GG': case 'gg': case 'HH': case 'hh': case 'mm': case 'ss': case 'ww': case 'WW': return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits; case 'M': case 'D': case 'd': case 'H': case 'h': case 'm': case 's': case 'w': case 'W': case 'e': case 'E': return parseTokenOneOrTwoDigits; case 'Do': return parseTokenOrdinal; default : a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), 'i')); return a; } } function timezoneMinutesFromString(string) { string = string || ''; var possibleTzMatches = (string.match(parseTokenTimezone) || []), tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [], parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0], minutes = +(parts[1] * 60) + toInt(parts[2]); return parts[0] === '+' ? -minutes : minutes; } // function to convert string input to date function addTimeToArrayFromToken(token, input, config) { var a, datePartArray = config._a; switch (token) { // QUARTER case 'Q': if (input != null) { datePartArray[MONTH] = (toInt(input) - 1) * 3; } break; // MONTH case 'M' : // fall through to MM case 'MM' : if (input != null) { datePartArray[MONTH] = toInt(input) - 1; } break; case 'MMM' : // fall through to MMMM case 'MMMM' : a = config._locale.monthsParse(input); // if we didn't find a month name, mark the date as invalid. if (a != null) { datePartArray[MONTH] = a; } else { config._pf.invalidMonth = input; } break; // DAY OF MONTH case 'D' : // fall through to DD case 'DD' : if (input != null) { datePartArray[DATE] = toInt(input); } break; case 'Do' : if (input != null) { datePartArray[DATE] = toInt(parseInt(input, 10)); } break; // DAY OF YEAR case 'DDD' : // fall through to DDDD case 'DDDD' : if (input != null) { config._dayOfYear = toInt(input); } break; // YEAR case 'YY' : datePartArray[YEAR] = moment.parseTwoDigitYear(input); break; case 'YYYY' : case 'YYYYY' : case 'YYYYYY' : datePartArray[YEAR] = toInt(input); break; // AM / PM case 'a' : // fall through to A case 'A' : config._isPm = config._locale.isPM(input); break; // 24 HOUR case 'H' : // fall through to hh case 'HH' : // fall through to hh case 'h' : // fall through to hh case 'hh' : datePartArray[HOUR] = toInt(input); break; // MINUTE case 'm' : // fall through to mm case 'mm' : datePartArray[MINUTE] = toInt(input); break; // SECOND case 's' : // fall through to ss case 'ss' : datePartArray[SECOND] = toInt(input); break; // MILLISECOND case 'S' : case 'SS' : case 'SSS' : case 'SSSS' : datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000); break; // UNIX TIMESTAMP WITH MS case 'X': config._d = new Date(parseFloat(input) * 1000); break; // TIMEZONE case 'Z' : // fall through to ZZ case 'ZZ' : config._useUTC = true; config._tzm = timezoneMinutesFromString(input); break; // WEEKDAY - human case 'dd': case 'ddd': case 'dddd': a = config._locale.weekdaysParse(input); // if we didn't get a weekday name, mark the date as invalid if (a != null) { config._w = config._w || {}; config._w['d'] = a; } else { config._pf.invalidWeekday = input; } break; // WEEK, WEEK DAY - numeric case 'w': case 'ww': case 'W': case 'WW': case 'd': case 'e': case 'E': token = token.substr(0, 1); /* falls through */ case 'gggg': case 'GGGG': case 'GGGGG': token = token.substr(0, 2); if (input) { config._w = config._w || {}; config._w[token] = toInt(input); } break; case 'gg': case 'GG': config._w = config._w || {}; config._w[token] = moment.parseTwoDigitYear(input); } } function dayOfYearFromWeekInfo(config) { var w, weekYear, week, weekday, dow, doy, temp; w = config._w; if (w.GG != null || w.W != null || w.E != null) { dow = 1; doy = 4; // TODO: We need to take the current isoWeekYear, but that depends on // how we interpret now (local, utc, fixed offset). So create // a now version of current config (take local/utc/offset flags, and // create now). weekYear = dfl(w.GG, config._a[YEAR], weekOfYear(moment(), 1, 4).year); week = dfl(w.W, 1); weekday = dfl(w.E, 1); } else { dow = config._locale._week.dow; doy = config._locale._week.doy; weekYear = dfl(w.gg, config._a[YEAR], weekOfYear(moment(), dow, doy).year); week = dfl(w.w, 1); if (w.d != null) { // weekday -- low day numbers are considered next week weekday = w.d; if (weekday < dow) { ++week; } } else if (w.e != null) { // local weekday -- counting starts from begining of week weekday = w.e + dow; } else { // default to begining of week weekday = dow; } } temp = dayOfYearFromWeeks(weekYear, week, weekday, doy, dow); config._a[YEAR] = temp.year; config._dayOfYear = temp.dayOfYear; } // convert an array to a date. // the array should mirror the parameters below // note: all values past the year are optional and will default to the lowest possible value. // [year, month, day , hour, minute, second, millisecond] function dateFromConfig(config) { var i, date, input = [], currentDate, yearToUse; if (config._d) { return; } currentDate = currentDateArray(config); //compute day of the year from weeks and weekdays if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { dayOfYearFromWeekInfo(config); } //if the day of the year is set, figure out what it is if (config._dayOfYear) { yearToUse = dfl(config._a[YEAR], currentDate[YEAR]); if (config._dayOfYear > daysInYear(yearToUse)) { config._pf._overflowDayOfYear = true; } date = makeUTCDate(yearToUse, 0, config._dayOfYear); config._a[MONTH] = date.getUTCMonth(); config._a[DATE] = date.getUTCDate(); } // Default to current date. // * if no year, month, day of month are given, default to today // * if day of month is given, default month and year // * if month is given, default only year // * if year is given, don't default anything for (i = 0; i < 3 && config._a[i] == null; ++i) { config._a[i] = input[i] = currentDate[i]; } // Zero out whatever was not defaulted, including time for (; i < 7; i++) { config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; } config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input); // Apply timezone offset from input. The actual zone can be changed // with parseZone. if (config._tzm != null) { config._d.setUTCMinutes(config._d.getUTCMinutes() + config._tzm); } } function dateFromObject(config) { var normalizedInput; if (config._d) { return; } normalizedInput = normalizeObjectUnits(config._i); config._a = [ normalizedInput.year, normalizedInput.month, normalizedInput.day, normalizedInput.hour, normalizedInput.minute, normalizedInput.second, normalizedInput.millisecond ]; dateFromConfig(config); } function currentDateArray(config) { var now = new Date(); if (config._useUTC) { return [ now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() ]; } else { return [now.getFullYear(), now.getMonth(), now.getDate()]; } } // date from string and format string function makeDateFromStringAndFormat(config) { if (config._f === moment.ISO_8601) { parseISO(config); return; } config._a = []; config._pf.empty = true; // This array is used to make a Date, either with `new Date` or `Date.UTC` var string = '' + config._i, i, parsedInput, tokens, token, skipped, stringLength = string.length, totalParsedInputLength = 0; tokens = expandFormat(config._f, config._locale).match(formattingTokens) || []; for (i = 0; i < tokens.length; i++) { token = tokens[i]; parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; if (parsedInput) { skipped = string.substr(0, string.indexOf(parsedInput)); if (skipped.length > 0) { config._pf.unusedInput.push(skipped); } string = string.slice(string.indexOf(parsedInput) + parsedInput.length); totalParsedInputLength += parsedInput.length; } // don't parse if it's not a known token if (formatTokenFunctions[token]) { if (parsedInput) { config._pf.empty = false; } else { config._pf.unusedTokens.push(token); } addTimeToArrayFromToken(token, parsedInput, config); } else if (config._strict && !parsedInput) { config._pf.unusedTokens.push(token); } } // add remaining unparsed input length to the string config._pf.charsLeftOver = stringLength - totalParsedInputLength; if (string.length > 0) { config._pf.unusedInput.push(string); } // handle am pm if (config._isPm && config._a[HOUR] < 12) { config._a[HOUR] += 12; } // if is 12 am, change hours to 0 if (config._isPm === false && config._a[HOUR] === 12) { config._a[HOUR] = 0; } dateFromConfig(config); checkOverflow(config); } function unescapeFormat(s) { return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) { return p1 || p2 || p3 || p4; }); } // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript function regexpEscape(s) { return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); } // date from string and array of format strings function makeDateFromStringAndArray(config) { var tempConfig, bestMoment, scoreToBeat, i, currentScore; if (config._f.length === 0) { config._pf.invalidFormat = true; config._d = new Date(NaN); return; } for (i = 0; i < config._f.length; i++) { currentScore = 0; tempConfig = copyConfig({}, config); tempConfig._pf = defaultParsingFlags(); tempConfig._f = config._f[i]; makeDateFromStringAndFormat(tempConfig); if (!isValid(tempConfig)) { continue; } // if there is any input that was not parsed add a penalty for that format currentScore += tempConfig._pf.charsLeftOver; //or tokens currentScore += tempConfig._pf.unusedTokens.length * 10; tempConfig._pf.score = currentScore; if (scoreToBeat == null || currentScore < scoreToBeat) { scoreToBeat = currentScore; bestMoment = tempConfig; } } extend(config, bestMoment || tempConfig); } // date from iso format function parseISO(config) { var i, l, string = config._i, match = isoRegex.exec(string); if (match) { config._pf.iso = true; for (i = 0, l = isoDates.length; i < l; i++) { if (isoDates[i][1].exec(string)) { // match[5] should be "T" or undefined config._f = isoDates[i][0] + (match[6] || ' '); break; } } for (i = 0, l = isoTimes.length; i < l; i++) { if (isoTimes[i][1].exec(string)) { config._f += isoTimes[i][0]; break; } } if (string.match(parseTokenTimezone)) { config._f += 'Z'; } makeDateFromStringAndFormat(config); } else { config._isValid = false; } } // date from iso format or fallback function makeDateFromString(config) { parseISO(config); if (config._isValid === false) { delete config._isValid; moment.createFromInputFallback(config); } } function makeDateFromInput(config) { var input = config._i, matched; if (input === undefined) { config._d = new Date(); } else if (isDate(input)) { config._d = new Date(+input); } else if ((matched = aspNetJsonRegex.exec(input)) !== null) { config._d = new Date(+matched[1]); } else if (typeof input === 'string') { makeDateFromString(config); } else if (isArray(input)) { config._a = input.slice(0); dateFromConfig(config); } else if (typeof(input) === 'object') { dateFromObject(config); } else if (typeof(input) === 'number') { // from milliseconds config._d = new Date(input); } else { moment.createFromInputFallback(config); } } function makeDate(y, m, d, h, M, s, ms) { //can't just apply() to create a date: //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply var date = new Date(y, m, d, h, M, s, ms); //the date constructor doesn't accept years < 1970 if (y < 1970) { date.setFullYear(y); } return date; } function makeUTCDate(y) { var date = new Date(Date.UTC.apply(null, arguments)); if (y < 1970) { date.setUTCFullYear(y); } return date; } function parseWeekday(input, locale) { if (typeof input === 'string') { if (!isNaN(input)) { input = parseInt(input, 10); } else { input = locale.weekdaysParse(input); if (typeof input !== 'number') { return null; } } } return input; } /************************************ Relative Time ************************************/ // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); } function relativeTime(posNegDuration, withoutSuffix, locale) { var duration = moment.duration(posNegDuration).abs(), seconds = round(duration.as('s')), minutes = round(duration.as('m')), hours = round(duration.as('h')), days = round(duration.as('d')), months = round(duration.as('M')), years = round(duration.as('y')), args = seconds < relativeTimeThresholds.s && ['s', seconds] || minutes === 1 && ['m'] || minutes < relativeTimeThresholds.m && ['mm', minutes] || hours === 1 && ['h'] || hours < relativeTimeThresholds.h && ['hh', hours] || days === 1 && ['d'] || days < relativeTimeThresholds.d && ['dd', days] || months === 1 && ['M'] || months < relativeTimeThresholds.M && ['MM', months] || years === 1 && ['y'] || ['yy', years]; args[2] = withoutSuffix; args[3] = +posNegDuration > 0; args[4] = locale; return substituteTimeAgo.apply({}, args); } /************************************ Week of Year ************************************/ // firstDayOfWeek 0 = sun, 6 = sat // the day of the week that starts the week // (usually sunday or monday) // firstDayOfWeekOfYear 0 = sun, 6 = sat // the first week is the week that contains the first // of this day of the week // (eg. ISO weeks use thursday (4)) function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) { var end = firstDayOfWeekOfYear - firstDayOfWeek, daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(), adjustedMoment; if (daysToDayOfWeek > end) { daysToDayOfWeek -= 7; } if (daysToDayOfWeek < end - 7) { daysToDayOfWeek += 7; } adjustedMoment = moment(mom).add(daysToDayOfWeek, 'd'); return { week: Math.ceil(adjustedMoment.dayOfYear() / 7), year: adjustedMoment.year() }; } //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) { var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear; d = d === 0 ? 7 : d; weekday = weekday != null ? weekday : firstDayOfWeek; daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0); dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1; return { year: dayOfYear > 0 ? year : year - 1, dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear }; } /************************************ Top Level Functions ************************************/ function makeMoment(config) { var input = config._i, format = config._f; config._locale = config._locale || moment.localeData(config._l); if (input === null || (format === undefined && input === '')) { return moment.invalid({nullInput: true}); } if (typeof input === 'string') { config._i = input = config._locale.preparse(input); } if (moment.isMoment(input)) { return new Moment(input, true); } else if (format) { if (isArray(format)) { makeDateFromStringAndArray(config); } else { makeDateFromStringAndFormat(config); } } else { makeDateFromInput(config); } return new Moment(config); } moment = function (input, format, locale, strict) { var c; if (typeof(locale) === "boolean") { strict = locale; locale = undefined; } // object construction must be done this way. // https://github.com/moment/moment/issues/1423 c = {}; c._isAMomentObject = true; c._i = input; c._f = format; c._l = locale; c._strict = strict; c._isUTC = false; c._pf = defaultParsingFlags(); return makeMoment(c); }; moment.suppressDeprecationWarnings = false; moment.createFromInputFallback = deprecate( 'moment construction falls back to js Date. This is ' + 'discouraged and will be removed in upcoming major ' + 'release. Please refer to ' + 'https://github.com/moment/moment/issues/1407 for more info.', function (config) { config._d = new Date(config._i); } ); // Pick a moment m from moments so that m[fn](other) is true for all // other. This relies on the function fn to be transitive. // // moments should either be an array of moment objects or an array, whose // first element is an array of moment objects. function pickBy(fn, moments) { var res, i; if (moments.length === 1 && isArray(moments[0])) { moments = moments[0]; } if (!moments.length) { return moment(); } res = moments[0]; for (i = 1; i < moments.length; ++i) { if (moments[i][fn](res)) { res = moments[i]; } } return res; } moment.min = function () { var args = [].slice.call(arguments, 0); return pickBy('isBefore', args); }; moment.max = function () { var args = [].slice.call(arguments, 0); return pickBy('isAfter', args); }; // creating with utc moment.utc = function (input, format, locale, strict) { var c; if (typeof(locale) === "boolean") { strict = locale; locale = undefined; } // object construction must be done this way. // https://github.com/moment/moment/issues/1423 c = {}; c._isAMomentObject = true; c._useUTC = true; c._isUTC = true; c._l = locale; c._i = input; c._f = format; c._strict = strict; c._pf = defaultParsingFlags(); return makeMoment(c).utc(); }; // creating with unix timestamp (in seconds) moment.unix = function (input) { return moment(input * 1000); }; // duration moment.duration = function (input, key) { var duration = input, // matching against regexp is expensive, do it on demand match = null, sign, ret, parseIso, diffRes; if (moment.isDuration(input)) { duration = { ms: input._milliseconds, d: input._days, M: input._months }; } else if (typeof input === 'number') { duration = {}; if (key) { duration[key] = input; } else { duration.milliseconds = input; } } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) { sign = (match[1] === '-') ? -1 : 1; duration = { y: 0, d: toInt(match[DATE]) * sign, h: toInt(match[HOUR]) * sign, m: toInt(match[MINUTE]) * sign, s: toInt(match[SECOND]) * sign, ms: toInt(match[MILLISECOND]) * sign }; } else if (!!(match = isoDurationRegex.exec(input))) { sign = (match[1] === '-') ? -1 : 1; parseIso = function (inp) { // We'd normally use ~~inp for this, but unfortunately it also // converts floats to ints. // inp may be undefined, so careful calling replace on it. var res = inp && parseFloat(inp.replace(',', '.')); // apply sign while we're at it return (isNaN(res) ? 0 : res) * sign; }; duration = { y: parseIso(match[2]), M: parseIso(match[3]), d: parseIso(match[4]), h: parseIso(match[5]), m: parseIso(match[6]), s: parseIso(match[7]), w: parseIso(match[8]) }; } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) { diffRes = momentsDifference(moment(duration.from), moment(duration.to)); duration = {}; duration.ms = diffRes.milliseconds; duration.M = diffRes.months; } ret = new Duration(duration); if (moment.isDuration(input) && input.hasOwnProperty('_locale')) { ret._locale = input._locale; } return ret; }; // version number moment.version = VERSION; // default format moment.defaultFormat = isoFormat; // constant that refers to the ISO standard moment.ISO_8601 = function () {}; // Plugins that add properties should also add the key here (null value), // so we can properly clone ourselves. moment.momentProperties = momentProperties; // This function will be called whenever a moment is mutated. // It is intended to keep the offset in sync with the timezone. moment.updateOffset = function () {}; // This function allows you to set a threshold for relative time strings moment.relativeTimeThreshold = function (threshold, limit) { if (relativeTimeThresholds[threshold] === undefined) { return false; } if (limit === undefined) { return relativeTimeThresholds[threshold]; } relativeTimeThresholds[threshold] = limit; return true; }; moment.lang = deprecate( "moment.lang is deprecated. Use moment.locale instead.", function (key, value) { return moment.locale(key, value); } ); // This function will load locale and then set the global locale. If // no arguments are passed in, it will simply return the current global // locale key. moment.locale = function (key, values) { var data; if (key) { if (typeof(values) !== "undefined") { data = moment.defineLocale(key, values); } else { data = moment.localeData(key); } if (data) { moment.duration._locale = moment._locale = data; } } return moment._locale._abbr; }; moment.defineLocale = function (name, values) { if (values !== null) { values.abbr = name; if (!locales[name]) { locales[name] = new Locale(); } locales[name].set(values); // backwards compat for now: also set the locale moment.locale(name); return locales[name]; } else { // useful for testing delete locales[name]; return null; } }; moment.langData = deprecate( "moment.langData is deprecated. Use moment.localeData instead.", function (key) { return moment.localeData(key); } ); // returns locale data moment.localeData = function (key) { var locale; if (key && key._locale && key._locale._abbr) { key = key._locale._abbr; } if (!key) { return moment._locale; } if (!isArray(key)) { //short-circuit everything else locale = loadLocale(key); if (locale) { return locale; } key = [key]; } return chooseLocale(key); }; // compare moment object moment.isMoment = function (obj) { return obj instanceof Moment || (obj != null && obj.hasOwnProperty('_isAMomentObject')); }; // for typechecking Duration objects moment.isDuration = function (obj) { return obj instanceof Duration; }; for (i = lists.length - 1; i >= 0; --i) { makeList(lists[i]); } moment.normalizeUnits = function (units) { return normalizeUnits(units); }; moment.invalid = function (flags) { var m = moment.utc(NaN); if (flags != null) { extend(m._pf, flags); } else { m._pf.userInvalidated = true; } return m; }; moment.parseZone = function () { return moment.apply(null, arguments).parseZone(); }; moment.parseTwoDigitYear = function (input) { return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); }; /************************************ Moment Prototype ************************************/ extend(moment.fn = Moment.prototype, { clone : function () { return moment(this); }, valueOf : function () { return +this._d + ((this._offset || 0) * 60000); }, unix : function () { return Math.floor(+this / 1000); }, toString : function () { return this.clone().locale('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ"); }, toDate : function () { return this._offset ? new Date(+this) : this._d; }, toISOString : function () { var m = moment(this).utc(); if (0 < m.year() && m.year() <= 9999) { return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); } else { return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); } }, toArray : function () { var m = this; return [ m.year(), m.month(), m.date(), m.hours(), m.minutes(), m.seconds(), m.milliseconds() ]; }, isValid : function () { return isValid(this); }, isDSTShifted : function () { if (this._a) { return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0; } return false; }, parsingFlags : function () { return extend({}, this._pf); }, invalidAt: function () { return this._pf.overflow; }, utc : function (keepLocalTime) { return this.zone(0, keepLocalTime); }, local : function (keepLocalTime) { if (this._isUTC) { this.zone(0, keepLocalTime); this._isUTC = false; if (keepLocalTime) { this.add(this._d.getTimezoneOffset(), 'm'); } } return this; }, format : function (inputString) { var output = formatMoment(this, inputString || moment.defaultFormat); return this.localeData().postformat(output); }, add : createAdder(1, 'add'), subtract : createAdder(-1, 'subtract'), diff : function (input, units, asFloat) { var that = makeAs(input, this), zoneDiff = (this.zone() - that.zone()) * 6e4, diff, output; units = normalizeUnits(units); if (units === 'year' || units === 'month') { // average number of days in the months in the given dates diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2 // difference in months output = ((this.year() - that.year()) * 12) + (this.month() - that.month()); // adjust by taking difference in days, average number of days // and dst in the given months. output += ((this - moment(this).startOf('month')) - (that - moment(that).startOf('month'))) / diff; // same as above but with zones, to negate all dst output -= ((this.zone() - moment(this).startOf('month').zone()) - (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff; if (units === 'year') { output = output / 12; } } else { diff = (this - that); output = units === 'second' ? diff / 1e3 : // 1000 units === 'minute' ? diff / 6e4 : // 1000 * 60 units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60 units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst diff; } return asFloat ? output : absRound(output); }, from : function (time, withoutSuffix) { return moment.duration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix); }, fromNow : function (withoutSuffix) { return this.from(moment(), withoutSuffix); }, calendar : function (time) { // We want to compare the start of today, vs this. // Getting start-of-today depends on whether we're zone'd or not. var now = time || moment(), sod = makeAs(now, this).startOf('day'), diff = this.diff(sod, 'days', true), format = diff < -6 ? 'sameElse' : diff < -1 ? 'lastWeek' : diff < 0 ? 'lastDay' : diff < 1 ? 'sameDay' : diff < 2 ? 'nextDay' : diff < 7 ? 'nextWeek' : 'sameElse'; return this.format(this.localeData().calendar(format, this)); }, isLeapYear : function () { return isLeapYear(this.year()); }, isDST : function () { return (this.zone() < this.clone().month(0).zone() || this.zone() < this.clone().month(5).zone()); }, day : function (input) { var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); if (input != null) { input = parseWeekday(input, this.localeData()); return this.add(input - day, 'd'); } else { return day; } }, month : makeAccessor('Month', true), startOf : function (units) { units = normalizeUnits(units); // the following switch intentionally omits break keywords // to utilize falling through the cases. switch (units) { case 'year': this.month(0); /* falls through */ case 'quarter': case 'month': this.date(1); /* falls through */ case 'week': case 'isoWeek': case 'day': this.hours(0); /* falls through */ case 'hour': this.minutes(0); /* falls through */ case 'minute': this.seconds(0); /* falls through */ case 'second': this.milliseconds(0); /* falls through */ } // weeks are a special case if (units === 'week') { this.weekday(0); } else if (units === 'isoWeek') { this.isoWeekday(1); } // quarters are also special if (units === 'quarter') { this.month(Math.floor(this.month() / 3) * 3); } return this; }, endOf: function (units) { units = normalizeUnits(units); return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms'); }, isAfter: function (input, units) { units = typeof units !== 'undefined' ? units : 'millisecond'; return +this.clone().startOf(units) > +moment(input).startOf(units); }, isBefore: function (input, units) { units = typeof units !== 'undefined' ? units : 'millisecond'; return +this.clone().startOf(units) < +moment(input).startOf(units); }, isSame: function (input, units) { units = units || 'ms'; return +this.clone().startOf(units) === +makeAs(input, this).startOf(units); }, min: deprecate( 'moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548', function (other) { other = moment.apply(null, arguments); return other < this ? this : other; } ), max: deprecate( 'moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548', function (other) { other = moment.apply(null, arguments); return other > this ? this : other; } ), // keepLocalTime = true means only change the timezone, without // affecting the local hour. So 5:31:26 +0300 --[zone(2, true)]--> // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist int zone // +0200, so we adjust the time as needed, to be valid. // // Keeping the time actually adds/subtracts (one hour) // from the actual represented time. That is why we call updateOffset // a second time. In case it wants us to change the offset again // _changeInProgress == true case, then we have to adjust, because // there is no such time in the given timezone. zone : function (input, keepLocalTime) { var offset = this._offset || 0, localAdjust; if (input != null) { if (typeof input === 'string') { input = timezoneMinutesFromString(input); } if (Math.abs(input) < 16) { input = input * 60; } if (!this._isUTC && keepLocalTime) { localAdjust = this._d.getTimezoneOffset(); } this._offset = input; this._isUTC = true; if (localAdjust != null) { this.subtract(localAdjust, 'm'); } if (offset !== input) { if (!keepLocalTime || this._changeInProgress) { addOrSubtractDurationFromMoment(this, moment.duration(offset - input, 'm'), 1, false); } else if (!this._changeInProgress) { this._changeInProgress = true; moment.updateOffset(this, true); this._changeInProgress = null; } } } else { return this._isUTC ? offset : this._d.getTimezoneOffset(); } return this; }, zoneAbbr : function () { return this._isUTC ? 'UTC' : ''; }, zoneName : function () { return this._isUTC ? 'Coordinated Universal Time' : ''; }, parseZone : function () { if (this._tzm) { this.zone(this._tzm); } else if (typeof this._i === 'string') { this.zone(this._i); } return this; }, hasAlignedHourOffset : function (input) { if (!input) { input = 0; } else { input = moment(input).zone(); } return (this.zone() - input) % 60 === 0; }, daysInMonth : function () { return daysInMonth(this.year(), this.month()); }, dayOfYear : function (input) { var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1; return input == null ? dayOfYear : this.add((input - dayOfYear), 'd'); }, quarter : function (input) { return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3); }, weekYear : function (input) { var year = weekOfYear(this, this.localeData()._week.dow, this.localeData()._week.doy).year; return input == null ? year : this.add((input - year), 'y'); }, isoWeekYear : function (input) { var year = weekOfYear(this, 1, 4).year; return input == null ? year : this.add((input - year), 'y'); }, week : function (input) { var week = this.localeData().week(this); return input == null ? week : this.add((input - week) * 7, 'd'); }, isoWeek : function (input) { var week = weekOfYear(this, 1, 4).week; return input == null ? week : this.add((input - week) * 7, 'd'); }, weekday : function (input) { var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; return input == null ? weekday : this.add(input - weekday, 'd'); }, isoWeekday : function (input) { // behaves the same as moment#day except // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) // as a setter, sunday should belong to the previous week. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7); }, isoWeeksInYear : function () { return weeksInYear(this.year(), 1, 4); }, weeksInYear : function () { var weekInfo = this.localeData()._week; return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); }, get : function (units) { units = normalizeUnits(units); return this[units](); }, set : function (units, value) { units = normalizeUnits(units); if (typeof this[units] === 'function') { this[units](value); } return this; }, // If passed a locale key, it will set the locale for this // instance. Otherwise, it will return the locale configuration // variables for this instance. locale : function (key) { if (key === undefined) { return this._locale._abbr; } else { this._locale = moment.localeData(key); return this; } }, lang : deprecate( "moment().lang() is deprecated. Use moment().localeData() instead.", function (key) { if (key === undefined) { return this.localeData(); } else { this._locale = moment.localeData(key); return this; } } ), localeData : function () { return this._locale; } }); function rawMonthSetter(mom, value) { var dayOfMonth; // TODO: Move this out of here! if (typeof value === 'string') { value = mom.localeData().monthsParse(value); // TODO: Another silent failure? if (typeof value !== 'number') { return mom; } } dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); return mom; } function rawGetter(mom, unit) { return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit](); } function rawSetter(mom, unit, value) { if (unit === 'Month') { return rawMonthSetter(mom, value); } else { return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); } } function makeAccessor(unit, keepTime) { return function (value) { if (value != null) { rawSetter(this, unit, value); moment.updateOffset(this, keepTime); return this; } else { return rawGetter(this, unit); } }; } moment.fn.millisecond = moment.fn.milliseconds = makeAccessor('Milliseconds', false); moment.fn.second = moment.fn.seconds = makeAccessor('Seconds', false); moment.fn.minute = moment.fn.minutes = makeAccessor('Minutes', false); // Setting the hour should keep the time, because the user explicitly // specified which hour he wants. So trying to maintain the same hour (in // a new timezone) makes sense. Adding/subtracting hours does not follow // this rule. moment.fn.hour = moment.fn.hours = makeAccessor('Hours', true); // moment.fn.month is defined separately moment.fn.date = makeAccessor('Date', true); moment.fn.dates = deprecate('dates accessor is deprecated. Use date instead.', makeAccessor('Date', true)); moment.fn.year = makeAccessor('FullYear', true); moment.fn.years = deprecate('years accessor is deprecated. Use year instead.', makeAccessor('FullYear', true)); // add plural methods moment.fn.days = moment.fn.day; moment.fn.months = moment.fn.month; moment.fn.weeks = moment.fn.week; moment.fn.isoWeeks = moment.fn.isoWeek; moment.fn.quarters = moment.fn.quarter; // add aliased format methods moment.fn.toJSON = moment.fn.toISOString; /************************************ Duration Prototype ************************************/ function daysToYears (days) { // 400 years have 146097 days (taking into account leap year rules) return days * 400 / 146097; } function yearsToDays (years) { // years * 365 + absRound(years / 4) - // absRound(years / 100) + absRound(years / 400); return years * 146097 / 400; } extend(moment.duration.fn = Duration.prototype, { _bubble : function () { var milliseconds = this._milliseconds, days = this._days, months = this._months, data = this._data, seconds, minutes, hours, years = 0; // The following code bubbles up values, see the tests for // examples of what that means. data.milliseconds = milliseconds % 1000; seconds = absRound(milliseconds / 1000); data.seconds = seconds % 60; minutes = absRound(seconds / 60); data.minutes = minutes % 60; hours = absRound(minutes / 60); data.hours = hours % 24; days += absRound(hours / 24); // Accurately convert days to years, assume start from year 0. years = absRound(daysToYears(days)); days -= absRound(yearsToDays(years)); // 30 days to a month // TODO (iskren): Use anchor date (like 1st Jan) to compute this. months += absRound(days / 30); days %= 30; // 12 months -> 1 year years += absRound(months / 12); months %= 12; data.days = days; data.months = months; data.years = years; }, abs : function () { this._milliseconds = Math.abs(this._milliseconds); this._days = Math.abs(this._days); this._months = Math.abs(this._months); this._data.milliseconds = Math.abs(this._data.milliseconds); this._data.seconds = Math.abs(this._data.seconds); this._data.minutes = Math.abs(this._data.minutes); this._data.hours = Math.abs(this._data.hours); this._data.months = Math.abs(this._data.months); this._data.years = Math.abs(this._data.years); return this; }, weeks : function () { return absRound(this.days() / 7); }, valueOf : function () { return this._milliseconds + this._days * 864e5 + (this._months % 12) * 2592e6 + toInt(this._months / 12) * 31536e6; }, humanize : function (withSuffix) { var output = relativeTime(this, !withSuffix, this.localeData()); if (withSuffix) { output = this.localeData().pastFuture(+this, output); } return this.localeData().postformat(output); }, add : function (input, val) { // supports only 2.0-style add(1, 's') or add(moment) var dur = moment.duration(input, val); this._milliseconds += dur._milliseconds; this._days += dur._days; this._months += dur._months; this._bubble(); return this; }, subtract : function (input, val) { var dur = moment.duration(input, val); this._milliseconds -= dur._milliseconds; this._days -= dur._days; this._months -= dur._months; this._bubble(); return this; }, get : function (units) { units = normalizeUnits(units); return this[units.toLowerCase() + 's'](); }, as : function (units) { var days, months; units = normalizeUnits(units); days = this._days + this._milliseconds / 864e5; if (units === 'month' || units === 'year') { months = this._months + daysToYears(days) * 12; return units === 'month' ? months : months / 12; } else { days += yearsToDays(this._months / 12); switch (units) { case 'week': return days / 7; case 'day': return days; case 'hour': return days * 24; case 'minute': return days * 24 * 60; case 'second': return days * 24 * 60 * 60; case 'millisecond': return days * 24 * 60 * 60 * 1000; default: throw new Error('Unknown unit ' + units); } } }, lang : moment.fn.lang, locale : moment.fn.locale, toIsoString : deprecate( "toIsoString() is deprecated. Please use toISOString() instead " + "(notice the capitals)", function () { return this.toISOString(); } ), toISOString : function () { // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js var years = Math.abs(this.years()), months = Math.abs(this.months()), days = Math.abs(this.days()), hours = Math.abs(this.hours()), minutes = Math.abs(this.minutes()), seconds = Math.abs(this.seconds() + this.milliseconds() / 1000); if (!this.asSeconds()) { // this is the same as C#'s (Noda) and python (isodate)... // but not other JS (goog.date) return 'P0D'; } return (this.asSeconds() < 0 ? '-' : '') + 'P' + (years ? years + 'Y' : '') + (months ? months + 'M' : '') + (days ? days + 'D' : '') + ((hours || minutes || seconds) ? 'T' : '') + (hours ? hours + 'H' : '') + (minutes ? minutes + 'M' : '') + (seconds ? seconds + 'S' : ''); }, localeData : function () { return this._locale; } }); function makeDurationGetter(name) { moment.duration.fn[name] = function () { return this._data[name]; }; } for (i in unitMillisecondFactors) { if (unitMillisecondFactors.hasOwnProperty(i)) { makeDurationGetter(i.toLowerCase()); } } moment.duration.fn.asMilliseconds = function () { return this.as('ms'); }; moment.duration.fn.asSeconds = function () { return this.as('s'); }; moment.duration.fn.asMinutes = function () { return this.as('m'); }; moment.duration.fn.asHours = function () { return this.as('h'); }; moment.duration.fn.asDays = function () { return this.as('d'); }; moment.duration.fn.asWeeks = function () { return this.as('weeks'); }; moment.duration.fn.asMonths = function () { return this.as('M'); }; moment.duration.fn.asYears = function () { return this.as('y'); }; /************************************ Default Locale ************************************/ // Set default locale, other locale will inherit from English. moment.locale('en', { ordinal : function (number) { var b = number % 10, output = (toInt(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; } }); /* EMBED_LOCALES */ /************************************ Exposing Moment ************************************/ function makeGlobal(shouldDeprecate) { /*global ender:false */ if (typeof ender !== 'undefined') { return; } oldGlobalMoment = globalScope.moment; if (shouldDeprecate) { globalScope.moment = deprecate( 'Accessing Moment through the global scope is ' + 'deprecated, and will be removed in an upcoming ' + 'release.', moment); } else { globalScope.moment = moment; } } // CommonJS module is defined if (hasModule) { module.exports = moment; } else if (true) { !(__WEBPACK_AMD_DEFINE_RESULT__ = (function (require, exports, module) { if (module.config && module.config() && module.config().noGlobal === true) { // release the global variable globalScope.moment = oldGlobalMoment; } return moment; }.call(exports, __webpack_require__, exports, module)), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); makeGlobal(true); } else { makeGlobal(); } }).call(this); /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(58)(module))) /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/*! Hammer.JS - v1.1.3 - 2014-05-20 * http://eightmedia.github.io/hammer.js * * Copyright (c) 2014 Jorik Tangelder <[email protected]>; * Licensed under the MIT license */ (function(window, undefined) { 'use strict'; /** * @main * @module hammer * * @class Hammer * @static */ /** * Hammer, use this to create instances * ```` * var hammertime = new Hammer(myElement); * ```` * * @method Hammer * @param {HTMLElement} element * @param {Object} [options={}] * @return {Hammer.Instance} */ var Hammer = function Hammer(element, options) { return new Hammer.Instance(element, options || {}); }; /** * version, as defined in package.json * the value will be set at each build * @property VERSION * @final * @type {String} */ Hammer.VERSION = '1.1.3'; /** * default settings. * more settings are defined per gesture at `/gestures`. Each gesture can be disabled/enabled * by setting it's name (like `swipe`) to false. * You can set the defaults for all instances by changing this object before creating an instance. * @example * ```` * Hammer.defaults.drag = false; * Hammer.defaults.behavior.touchAction = 'pan-y'; * delete Hammer.defaults.behavior.userSelect; * ```` * @property defaults * @type {Object} */ Hammer.defaults = { /** * this setting object adds styles and attributes to the element to prevent the browser from doing * its native behavior. The css properties are auto prefixed for the browsers when needed. * @property defaults.behavior * @type {Object} */ behavior: { /** * Disables text selection to improve the dragging gesture. When the value is `none` it also sets * `onselectstart=false` for IE on the element. Mainly for desktop browsers. * @property defaults.behavior.userSelect * @type {String} * @default 'none' */ userSelect: 'none', /** * Specifies whether and how a given region can be manipulated by the user (for instance, by panning or zooming). * Used by Chrome 35> and IE10>. By default this makes the element blocking any touch event. * @property defaults.behavior.touchAction * @type {String} * @default: 'pan-y' */ touchAction: 'pan-y', /** * Disables the default callout shown when you touch and hold a touch target. * On iOS, when you touch and hold a touch target such as a link, Safari displays * a callout containing information about the link. This property allows you to disable that callout. * @property defaults.behavior.touchCallout * @type {String} * @default 'none' */ touchCallout: 'none', /** * Specifies whether zooming is enabled. Used by IE10> * @property defaults.behavior.contentZooming * @type {String} * @default 'none' */ contentZooming: 'none', /** * Specifies that an entire element should be draggable instead of its contents. * Mainly for desktop browsers. * @property defaults.behavior.userDrag * @type {String} * @default 'none' */ userDrag: 'none', /** * Overrides the highlight color shown when the user taps a link or a JavaScript * clickable element in Safari on iPhone. This property obeys the alpha value, if specified. * * If you don't specify an alpha value, Safari on iPhone applies a default alpha value * to the color. To disable tap highlighting, set the alpha value to 0 (invisible). * If you set the alpha value to 1.0 (opaque), the element is not visible when tapped. * @property defaults.behavior.tapHighlightColor * @type {String} * @default 'rgba(0,0,0,0)' */ tapHighlightColor: 'rgba(0,0,0,0)' } }; /** * hammer document where the base events are added at * @property DOCUMENT * @type {HTMLElement} * @default window.document */ Hammer.DOCUMENT = document; /** * detect support for pointer events * @property HAS_POINTEREVENTS * @type {Boolean} */ Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled; /** * detect support for touch events * @property HAS_TOUCHEVENTS * @type {Boolean} */ Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window); /** * detect mobile browsers * @property IS_MOBILE * @type {Boolean} */ Hammer.IS_MOBILE = /mobile|tablet|ip(ad|hone|od)|android|silk/i.test(navigator.userAgent); /** * detect if we want to support mouseevents at all * @property NO_MOUSEEVENTS * @type {Boolean} */ Hammer.NO_MOUSEEVENTS = (Hammer.HAS_TOUCHEVENTS && Hammer.IS_MOBILE) || Hammer.HAS_POINTEREVENTS; /** * interval in which Hammer recalculates current velocity/direction/angle in ms * @property CALCULATE_INTERVAL * @type {Number} * @default 25 */ Hammer.CALCULATE_INTERVAL = 25; /** * eventtypes per touchevent (start, move, end) are filled by `Event.determineEventTypes` on `setup` * the object contains the DOM event names per type (`EVENT_START`, `EVENT_MOVE`, `EVENT_END`) * @property EVENT_TYPES * @private * @writeOnce * @type {Object} */ var EVENT_TYPES = {}; /** * direction strings, for safe comparisons * @property DIRECTION_DOWN|LEFT|UP|RIGHT * @final * @type {String} * @default 'down' 'left' 'up' 'right' */ var DIRECTION_DOWN = Hammer.DIRECTION_DOWN = 'down'; var DIRECTION_LEFT = Hammer.DIRECTION_LEFT = 'left'; var DIRECTION_UP = Hammer.DIRECTION_UP = 'up'; var DIRECTION_RIGHT = Hammer.DIRECTION_RIGHT = 'right'; /** * pointertype strings, for safe comparisons * @property POINTER_MOUSE|TOUCH|PEN * @final * @type {String} * @default 'mouse' 'touch' 'pen' */ var POINTER_MOUSE = Hammer.POINTER_MOUSE = 'mouse'; var POINTER_TOUCH = Hammer.POINTER_TOUCH = 'touch'; var POINTER_PEN = Hammer.POINTER_PEN = 'pen'; /** * eventtypes * @property EVENT_START|MOVE|END|RELEASE|TOUCH * @final * @type {String} * @default 'start' 'change' 'move' 'end' 'release' 'touch' */ var EVENT_START = Hammer.EVENT_START = 'start'; var EVENT_MOVE = Hammer.EVENT_MOVE = 'move'; var EVENT_END = Hammer.EVENT_END = 'end'; var EVENT_RELEASE = Hammer.EVENT_RELEASE = 'release'; var EVENT_TOUCH = Hammer.EVENT_TOUCH = 'touch'; /** * if the window events are set... * @property READY * @writeOnce * @type {Boolean} * @default false */ Hammer.READY = false; /** * plugins namespace * @property plugins * @type {Object} */ Hammer.plugins = Hammer.plugins || {}; /** * gestures namespace * see `/gestures` for the definitions * @property gestures * @type {Object} */ Hammer.gestures = Hammer.gestures || {}; /** * setup events to detect gestures on the document * this function is called when creating an new instance * @private */ function setup() { if(Hammer.READY) { return; } // find what eventtypes we add listeners to Event.determineEventTypes(); // Register all gestures inside Hammer.gestures Utils.each(Hammer.gestures, function(gesture) { Detection.register(gesture); }); // Add touch events on the document Event.onTouch(Hammer.DOCUMENT, EVENT_MOVE, Detection.detect); Event.onTouch(Hammer.DOCUMENT, EVENT_END, Detection.detect); // Hammer is ready...! Hammer.READY = true; } /** * @module hammer * * @class Utils * @static */ var Utils = Hammer.utils = { /** * extend method, could also be used for cloning when `dest` is an empty object. * changes the dest object * @method extend * @param {Object} dest * @param {Object} src * @param {Boolean} [merge=false] do a merge * @return {Object} dest */ extend: function extend(dest, src, merge) { for(var key in src) { if(!src.hasOwnProperty(key) || (dest[key] !== undefined && merge)) { continue; } dest[key] = src[key]; } return dest; }, /** * simple addEventListener wrapper * @method on * @param {HTMLElement} element * @param {String} type * @param {Function} handler */ on: function on(element, type, handler) { element.addEventListener(type, handler, false); }, /** * simple removeEventListener wrapper * @method off * @param {HTMLElement} element * @param {String} type * @param {Function} handler */ off: function off(element, type, handler) { element.removeEventListener(type, handler, false); }, /** * forEach over arrays and objects * @method each * @param {Object|Array} obj * @param {Function} iterator * @param {any} iterator.item * @param {Number} iterator.index * @param {Object|Array} iterator.obj the source object * @param {Object} context value to use as `this` in the iterator */ each: function each(obj, iterator, context) { var i, len; // native forEach on arrays if('forEach' in obj) { obj.forEach(iterator, context); // arrays } else if(obj.length !== undefined) { for(i = 0, len = obj.length; i < len; i++) { if(iterator.call(context, obj[i], i, obj) === false) { return; } } // objects } else { for(i in obj) { if(obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj) === false) { return; } } } }, /** * find if a string contains the string using indexOf * @method inStr * @param {String} src * @param {String} find * @return {Boolean} found */ inStr: function inStr(src, find) { return src.indexOf(find) > -1; }, /** * find if a array contains the object using indexOf or a simple polyfill * @method inArray * @param {String} src * @param {String} find * @return {Boolean|Number} false when not found, or the index */ inArray: function inArray(src, find) { if(src.indexOf) { var index = src.indexOf(find); return (index === -1) ? false : index; } else { for(var i = 0, len = src.length; i < len; i++) { if(src[i] === find) { return i; } } return false; } }, /** * convert an array-like object (`arguments`, `touchlist`) to an array * @method toArray * @param {Object} obj * @return {Array} */ toArray: function toArray(obj) { return Array.prototype.slice.call(obj, 0); }, /** * find if a node is in the given parent * @method hasParent * @param {HTMLElement} node * @param {HTMLElement} parent * @return {Boolean} found */ hasParent: function hasParent(node, parent) { while(node) { if(node == parent) { return true; } node = node.parentNode; } return false; }, /** * get the center of all the touches * @method getCenter * @param {Array} touches * @return {Object} center contains `pageX`, `pageY`, `clientX` and `clientY` properties */ getCenter: function getCenter(touches) { var pageX = [], pageY = [], clientX = [], clientY = [], min = Math.min, max = Math.max; // no need to loop when only one touch if(touches.length === 1) { return { pageX: touches[0].pageX, pageY: touches[0].pageY, clientX: touches[0].clientX, clientY: touches[0].clientY }; } Utils.each(touches, function(touch) { pageX.push(touch.pageX); pageY.push(touch.pageY); clientX.push(touch.clientX); clientY.push(touch.clientY); }); return { pageX: (min.apply(Math, pageX) + max.apply(Math, pageX)) / 2, pageY: (min.apply(Math, pageY) + max.apply(Math, pageY)) / 2, clientX: (min.apply(Math, clientX) + max.apply(Math, clientX)) / 2, clientY: (min.apply(Math, clientY) + max.apply(Math, clientY)) / 2 }; }, /** * calculate the velocity between two points. unit is in px per ms. * @method getVelocity * @param {Number} deltaTime * @param {Number} deltaX * @param {Number} deltaY * @return {Object} velocity `x` and `y` */ getVelocity: function getVelocity(deltaTime, deltaX, deltaY) { return { x: Math.abs(deltaX / deltaTime) || 0, y: Math.abs(deltaY / deltaTime) || 0 }; }, /** * calculate the angle between two coordinates * @method getAngle * @param {Touch} touch1 * @param {Touch} touch2 * @return {Number} angle */ getAngle: function getAngle(touch1, touch2) { var x = touch2.clientX - touch1.clientX, y = touch2.clientY - touch1.clientY; return Math.atan2(y, x) * 180 / Math.PI; }, /** * do a small comparision to get the direction between two touches. * @method getDirection * @param {Touch} touch1 * @param {Touch} touch2 * @return {String} direction matches `DIRECTION_LEFT|RIGHT|UP|DOWN` */ getDirection: function getDirection(touch1, touch2) { var x = Math.abs(touch1.clientX - touch2.clientX), y = Math.abs(touch1.clientY - touch2.clientY); if(x >= y) { return touch1.clientX - touch2.clientX > 0 ? DIRECTION_LEFT : DIRECTION_RIGHT; } return touch1.clientY - touch2.clientY > 0 ? DIRECTION_UP : DIRECTION_DOWN; }, /** * calculate the distance between two touches * @method getDistance * @param {Touch}touch1 * @param {Touch} touch2 * @return {Number} distance */ getDistance: function getDistance(touch1, touch2) { var x = touch2.clientX - touch1.clientX, y = touch2.clientY - touch1.clientY; return Math.sqrt((x * x) + (y * y)); }, /** * calculate the scale factor between two touchLists * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out * @method getScale * @param {Array} start array of touches * @param {Array} end array of touches * @return {Number} scale */ getScale: function getScale(start, end) { // need two fingers... if(start.length >= 2 && end.length >= 2) { return this.getDistance(end[0], end[1]) / this.getDistance(start[0], start[1]); } return 1; }, /** * calculate the rotation degrees between two touchLists * @method getRotation * @param {Array} start array of touches * @param {Array} end array of touches * @return {Number} rotation */ getRotation: function getRotation(start, end) { // need two fingers if(start.length >= 2 && end.length >= 2) { return this.getAngle(end[1], end[0]) - this.getAngle(start[1], start[0]); } return 0; }, /** * find out if the direction is vertical * * @method isVertical * @param {String} direction matches `DIRECTION_UP|DOWN` * @return {Boolean} is_vertical */ isVertical: function isVertical(direction) { return direction == DIRECTION_UP || direction == DIRECTION_DOWN; }, /** * set css properties with their prefixes * @param {HTMLElement} element * @param {String} prop * @param {String} value * @param {Boolean} [toggle=true] * @return {Boolean} */ setPrefixedCss: function setPrefixedCss(element, prop, value, toggle) { var prefixes = ['', 'Webkit', 'Moz', 'O', 'ms']; prop = Utils.toCamelCase(prop); for(var i = 0; i < prefixes.length; i++) { var p = prop; // prefixes if(prefixes[i]) { p = prefixes[i] + p.slice(0, 1).toUpperCase() + p.slice(1); } // test the style if(p in element.style) { element.style[p] = (toggle == null || toggle) && value || ''; break; } } }, /** * toggle browser default behavior by setting css properties. * `userSelect='none'` also sets `element.onselectstart` to false * `userDrag='none'` also sets `element.ondragstart` to false * * @method toggleBehavior * @param {HtmlElement} element * @param {Object} props * @param {Boolean} [toggle=true] */ toggleBehavior: function toggleBehavior(element, props, toggle) { if(!props || !element || !element.style) { return; } // set the css properties Utils.each(props, function(value, prop) { Utils.setPrefixedCss(element, prop, value, toggle); }); var falseFn = toggle && function() { return false; }; // also the disable onselectstart if(props.userSelect == 'none') { element.onselectstart = falseFn; } // and disable ondragstart if(props.userDrag == 'none') { element.ondragstart = falseFn; } }, /** * convert a string with underscores to camelCase * so prevent_default becomes preventDefault * @param {String} str * @return {String} camelCaseStr */ toCamelCase: function toCamelCase(str) { return str.replace(/[_-]([a-z])/g, function(s) { return s[1].toUpperCase(); }); } }; /** * @module hammer */ /** * @class Event * @static */ var Event = Hammer.event = { /** * when touch events have been fired, this is true * this is used to stop mouse events * @property prevent_mouseevents * @private * @type {Boolean} */ preventMouseEvents: false, /** * if EVENT_START has been fired * @property started * @private * @type {Boolean} */ started: false, /** * when the mouse is hold down, this is true * @property should_detect * @private * @type {Boolean} */ shouldDetect: false, /** * simple event binder with a hook and support for multiple types * @method on * @param {HTMLElement} element * @param {String} type * @param {Function} handler * @param {Function} [hook] * @param {Object} hook.type */ on: function on(element, type, handler, hook) { var types = type.split(' '); Utils.each(types, function(type) { Utils.on(element, type, handler); hook && hook(type); }); }, /** * simple event unbinder with a hook and support for multiple types * @method off * @param {HTMLElement} element * @param {String} type * @param {Function} handler * @param {Function} [hook] * @param {Object} hook.type */ off: function off(element, type, handler, hook) { var types = type.split(' '); Utils.each(types, function(type) { Utils.off(element, type, handler); hook && hook(type); }); }, /** * the core touch event handler. * this finds out if we should to detect gestures * @method onTouch * @param {HTMLElement} element * @param {String} eventType matches `EVENT_START|MOVE|END` * @param {Function} handler * @return onTouchHandler {Function} the core event handler */ onTouch: function onTouch(element, eventType, handler) { var self = this; var onTouchHandler = function onTouchHandler(ev) { var srcType = ev.type.toLowerCase(), isPointer = Hammer.HAS_POINTEREVENTS, isMouse = Utils.inStr(srcType, 'mouse'), triggerType; // if we are in a mouseevent, but there has been a touchevent triggered in this session // we want to do nothing. simply break out of the event. if(isMouse && self.preventMouseEvents) { return; // mousebutton must be down } else if(isMouse && eventType == EVENT_START && ev.button === 0) { self.preventMouseEvents = false; self.shouldDetect = true; } else if(isPointer && eventType == EVENT_START) { self.shouldDetect = (ev.buttons === 1 || PointerEvent.matchType(POINTER_TOUCH, ev)); // just a valid start event, but no mouse } else if(!isMouse && eventType == EVENT_START) { self.preventMouseEvents = true; self.shouldDetect = true; } // update the pointer event before entering the detection if(isPointer && eventType != EVENT_END) { PointerEvent.updatePointer(eventType, ev); } // we are in a touch/down state, so allowed detection of gestures if(self.shouldDetect) { triggerType = self.doDetect.call(self, ev, eventType, element, handler); } // ...and we are done with the detection // so reset everything to start each detection totally fresh if(triggerType == EVENT_END) { self.preventMouseEvents = false; self.shouldDetect = false; PointerEvent.reset(); // update the pointerevent object after the detection } if(isPointer && eventType == EVENT_END) { PointerEvent.updatePointer(eventType, ev); } }; this.on(element, EVENT_TYPES[eventType], onTouchHandler); return onTouchHandler; }, /** * the core detection method * this finds out what hammer-touch-events to trigger * @method doDetect * @param {Object} ev * @param {String} eventType matches `EVENT_START|MOVE|END` * @param {HTMLElement} element * @param {Function} handler * @return {String} triggerType matches `EVENT_START|MOVE|END` */ doDetect: function doDetect(ev, eventType, element, handler) { var touchList = this.getTouchList(ev, eventType); var touchListLength = touchList.length; var triggerType = eventType; var triggerChange = touchList.trigger; // used by fakeMultitouch plugin var changedLength = touchListLength; // at each touchstart-like event we want also want to trigger a TOUCH event... if(eventType == EVENT_START) { triggerChange = EVENT_TOUCH; // ...the same for a touchend-like event } else if(eventType == EVENT_END) { triggerChange = EVENT_RELEASE; // keep track of how many touches have been removed changedLength = touchList.length - ((ev.changedTouches) ? ev.changedTouches.length : 1); } // after there are still touches on the screen, // we just want to trigger a MOVE event. so change the START or END to a MOVE // but only after detection has been started, the first time we actualy want a START if(changedLength > 0 && this.started) { triggerType = EVENT_MOVE; } // detection has been started, we keep track of this, see above this.started = true; // generate some event data, some basic information var evData = this.collectEventData(element, triggerType, touchList, ev); // trigger the triggerType event before the change (TOUCH, RELEASE) events // but the END event should be at last if(eventType != EVENT_END) { handler.call(Detection, evData); } // trigger a change (TOUCH, RELEASE) event, this means the length of the touches changed if(triggerChange) { evData.changedLength = changedLength; evData.eventType = triggerChange; handler.call(Detection, evData); evData.eventType = triggerType; delete evData.changedLength; } // trigger the END event if(triggerType == EVENT_END) { handler.call(Detection, evData); // ...and we are done with the detection // so reset everything to start each detection totally fresh this.started = false; } return triggerType; }, /** * we have different events for each device/browser * determine what we need and set them in the EVENT_TYPES constant * the `onTouch` method is bind to these properties. * @method determineEventTypes * @return {Object} events */ determineEventTypes: function determineEventTypes() { var types; if(Hammer.HAS_POINTEREVENTS) { if(window.PointerEvent) { types = [ 'pointerdown', 'pointermove', 'pointerup pointercancel lostpointercapture' ]; } else { types = [ 'MSPointerDown', 'MSPointerMove', 'MSPointerUp MSPointerCancel MSLostPointerCapture' ]; } } else if(Hammer.NO_MOUSEEVENTS) { types = [ 'touchstart', 'touchmove', 'touchend touchcancel' ]; } else { types = [ 'touchstart mousedown', 'touchmove mousemove', 'touchend touchcancel mouseup' ]; } EVENT_TYPES[EVENT_START] = types[0]; EVENT_TYPES[EVENT_MOVE] = types[1]; EVENT_TYPES[EVENT_END] = types[2]; return EVENT_TYPES; }, /** * create touchList depending on the event * @method getTouchList * @param {Object} ev * @param {String} eventType * @return {Array} touches */ getTouchList: function getTouchList(ev, eventType) { // get the fake pointerEvent touchlist if(Hammer.HAS_POINTEREVENTS) { return PointerEvent.getTouchList(); } // get the touchlist if(ev.touches) { if(eventType == EVENT_MOVE) { return ev.touches; } var identifiers = []; var concat = [].concat(Utils.toArray(ev.touches), Utils.toArray(ev.changedTouches)); var touchList = []; Utils.each(concat, function(touch) { if(Utils.inArray(identifiers, touch.identifier) === false) { touchList.push(touch); } identifiers.push(touch.identifier); }); return touchList; } // make fake touchList from mouse position ev.identifier = 1; return [ev]; }, /** * collect basic event data * @method collectEventData * @param {HTMLElement} element * @param {String} eventType matches `EVENT_START|MOVE|END` * @param {Array} touches * @param {Object} ev * @return {Object} ev */ collectEventData: function collectEventData(element, eventType, touches, ev) { // find out pointerType var pointerType = POINTER_TOUCH; if(Utils.inStr(ev.type, 'mouse') || PointerEvent.matchType(POINTER_MOUSE, ev)) { pointerType = POINTER_MOUSE; } else if(PointerEvent.matchType(POINTER_PEN, ev)) { pointerType = POINTER_PEN; } return { center: Utils.getCenter(touches), timeStamp: Date.now(), target: ev.target, touches: touches, eventType: eventType, pointerType: pointerType, srcEvent: ev, /** * prevent the browser default actions * mostly used to disable scrolling of the browser */ preventDefault: function() { var srcEvent = this.srcEvent; srcEvent.preventManipulation && srcEvent.preventManipulation(); srcEvent.preventDefault && srcEvent.preventDefault(); }, /** * stop bubbling the event up to its parents */ stopPropagation: function() { this.srcEvent.stopPropagation(); }, /** * immediately stop gesture detection * might be useful after a swipe was detected * @return {*} */ stopDetect: function() { return Detection.stopDetect(); } }; } }; /** * @module hammer * * @class PointerEvent * @static */ var PointerEvent = Hammer.PointerEvent = { /** * holds all pointers, by `identifier` * @property pointers * @type {Object} */ pointers: {}, /** * get the pointers as an array * @method getTouchList * @return {Array} touchlist */ getTouchList: function getTouchList() { var touchlist = []; // we can use forEach since pointerEvents only is in IE10 Utils.each(this.pointers, function(pointer) { touchlist.push(pointer); }); return touchlist; }, /** * update the position of a pointer * @method updatePointer * @param {String} eventType matches `EVENT_START|MOVE|END` * @param {Object} pointerEvent */ updatePointer: function updatePointer(eventType, pointerEvent) { if(eventType == EVENT_END || (eventType != EVENT_END && pointerEvent.buttons !== 1)) { delete this.pointers[pointerEvent.pointerId]; } else { pointerEvent.identifier = pointerEvent.pointerId; this.pointers[pointerEvent.pointerId] = pointerEvent; } }, /** * check if ev matches pointertype * @method matchType * @param {String} pointerType matches `POINTER_MOUSE|TOUCH|PEN` * @param {PointerEvent} ev */ matchType: function matchType(pointerType, ev) { if(!ev.pointerType) { return false; } var pt = ev.pointerType, types = {}; types[POINTER_MOUSE] = (pt === (ev.MSPOINTER_TYPE_MOUSE || POINTER_MOUSE)); types[POINTER_TOUCH] = (pt === (ev.MSPOINTER_TYPE_TOUCH || POINTER_TOUCH)); types[POINTER_PEN] = (pt === (ev.MSPOINTER_TYPE_PEN || POINTER_PEN)); return types[pointerType]; }, /** * reset the stored pointers * @method reset */ reset: function resetList() { this.pointers = {}; } }; /** * @module hammer * * @class Detection * @static */ var Detection = Hammer.detection = { // contains all registred Hammer.gestures in the correct order gestures: [], // data of the current Hammer.gesture detection session current: null, // the previous Hammer.gesture session data // is a full clone of the previous gesture.current object previous: null, // when this becomes true, no gestures are fired stopped: false, /** * start Hammer.gesture detection * @method startDetect * @param {Hammer.Instance} inst * @param {Object} eventData */ startDetect: function startDetect(inst, eventData) { // already busy with a Hammer.gesture detection on an element if(this.current) { return; } this.stopped = false; // holds current session this.current = { inst: inst, // reference to HammerInstance we're working for startEvent: Utils.extend({}, eventData), // start eventData for distances, timing etc lastEvent: false, // last eventData lastCalcEvent: false, // last eventData for calculations. futureCalcEvent: false, // last eventData for calculations. lastCalcData: {}, // last lastCalcData name: '' // current gesture we're in/detected, can be 'tap', 'hold' etc }; this.detect(eventData); }, /** * Hammer.gesture detection * @method detect * @param {Object} eventData * @return {any} */ detect: function detect(eventData) { if(!this.current || this.stopped) { return; } // extend event data with calculations about scale, distance etc eventData = this.extendEventData(eventData); // hammer instance and instance options var inst = this.current.inst, instOptions = inst.options; // call Hammer.gesture handlers Utils.each(this.gestures, function triggerGesture(gesture) { // only when the instance options have enabled this gesture if(!this.stopped && inst.enabled && instOptions[gesture.name]) { gesture.handler.call(gesture, eventData, inst); } }, this); // store as previous event event if(this.current) { this.current.lastEvent = eventData; } if(eventData.eventType == EVENT_END) { this.stopDetect(); } return eventData; }, /** * clear the Hammer.gesture vars * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected * to stop other Hammer.gestures from being fired * @method stopDetect */ stopDetect: function stopDetect() { // clone current data to the store as the previous gesture // used for the double tap gesture, since this is an other gesture detect session this.previous = Utils.extend({}, this.current); // reset the current this.current = null; this.stopped = true; }, /** * calculate velocity, angle and direction * @method getVelocityData * @param {Object} ev * @param {Object} center * @param {Number} deltaTime * @param {Number} deltaX * @param {Number} deltaY */ getCalculatedData: function getCalculatedData(ev, center, deltaTime, deltaX, deltaY) { var cur = this.current, recalc = false, calcEv = cur.lastCalcEvent, calcData = cur.lastCalcData; if(calcEv && ev.timeStamp - calcEv.timeStamp > Hammer.CALCULATE_INTERVAL) { center = calcEv.center; deltaTime = ev.timeStamp - calcEv.timeStamp; deltaX = ev.center.clientX - calcEv.center.clientX; deltaY = ev.center.clientY - calcEv.center.clientY; recalc = true; } if(ev.eventType == EVENT_TOUCH || ev.eventType == EVENT_RELEASE) { cur.futureCalcEvent = ev; } if(!cur.lastCalcEvent || recalc) { calcData.velocity = Utils.getVelocity(deltaTime, deltaX, deltaY); calcData.angle = Utils.getAngle(center, ev.center); calcData.direction = Utils.getDirection(center, ev.center); cur.lastCalcEvent = cur.futureCalcEvent || ev; cur.futureCalcEvent = ev; } ev.velocityX = calcData.velocity.x; ev.velocityY = calcData.velocity.y; ev.interimAngle = calcData.angle; ev.interimDirection = calcData.direction; }, /** * extend eventData for Hammer.gestures * @method extendEventData * @param {Object} ev * @return {Object} ev */ extendEventData: function extendEventData(ev) { var cur = this.current, startEv = cur.startEvent, lastEv = cur.lastEvent || startEv; // update the start touchlist to calculate the scale/rotation if(ev.eventType == EVENT_TOUCH || ev.eventType == EVENT_RELEASE) { startEv.touches = []; Utils.each(ev.touches, function(touch) { startEv.touches.push({ clientX: touch.clientX, clientY: touch.clientY }); }); } var deltaTime = ev.timeStamp - startEv.timeStamp, deltaX = ev.center.clientX - startEv.center.clientX, deltaY = ev.center.clientY - startEv.center.clientY; this.getCalculatedData(ev, lastEv.center, deltaTime, deltaX, deltaY); Utils.extend(ev, { startEvent: startEv, deltaTime: deltaTime, deltaX: deltaX, deltaY: deltaY, distance: Utils.getDistance(startEv.center, ev.center), angle: Utils.getAngle(startEv.center, ev.center), direction: Utils.getDirection(startEv.center, ev.center), scale: Utils.getScale(startEv.touches, ev.touches), rotation: Utils.getRotation(startEv.touches, ev.touches) }); return ev; }, /** * register new gesture * @method register * @param {Object} gesture object, see `gestures/` for documentation * @return {Array} gestures */ register: function register(gesture) { // add an enable gesture options if there is no given var options = gesture.defaults || {}; if(options[gesture.name] === undefined) { options[gesture.name] = true; } // extend Hammer default options with the Hammer.gesture options Utils.extend(Hammer.defaults, options, true); // set its index gesture.index = gesture.index || 1000; // add Hammer.gesture to the list this.gestures.push(gesture); // sort the list by index this.gestures.sort(function(a, b) { if(a.index < b.index) { return -1; } if(a.index > b.index) { return 1; } return 0; }); return this.gestures; } }; /** * @module hammer */ /** * create new hammer instance * all methods should return the instance itself, so it is chainable. * * @class Instance * @constructor * @param {HTMLElement} element * @param {Object} [options={}] options are merged with `Hammer.defaults` * @return {Hammer.Instance} */ Hammer.Instance = function(element, options) { var self = this; // setup HammerJS window events and register all gestures // this also sets up the default options setup(); /** * @property element * @type {HTMLElement} */ this.element = element; /** * @property enabled * @type {Boolean} * @protected */ this.enabled = true; /** * options, merged with the defaults * options with an _ are converted to camelCase * @property options * @type {Object} */ Utils.each(options, function(value, name) { delete options[name]; options[Utils.toCamelCase(name)] = value; }); this.options = Utils.extend(Utils.extend({}, Hammer.defaults), options || {}); // add some css to the element to prevent the browser from doing its native behavoir if(this.options.behavior) { Utils.toggleBehavior(this.element, this.options.behavior, true); } /** * event start handler on the element to start the detection * @property eventStartHandler * @type {Object} */ this.eventStartHandler = Event.onTouch(element, EVENT_START, function(ev) { if(self.enabled && ev.eventType == EVENT_START) { Detection.startDetect(self, ev); } else if(ev.eventType == EVENT_TOUCH) { Detection.detect(ev); } }); /** * keep a list of user event handlers which needs to be removed when calling 'dispose' * @property eventHandlers * @type {Array} */ this.eventHandlers = []; }; Hammer.Instance.prototype = { /** * bind events to the instance * @method on * @chainable * @param {String} gestures multiple gestures by splitting with a space * @param {Function} handler * @param {Object} handler.ev event object */ on: function onEvent(gestures, handler) { var self = this; Event.on(self.element, gestures, handler, function(type) { self.eventHandlers.push({ gesture: type, handler: handler }); }); return self; }, /** * unbind events to the instance * @method off * @chainable * @param {String} gestures * @param {Function} handler */ off: function offEvent(gestures, handler) { var self = this; Event.off(self.element, gestures, handler, function(type) { var index = Utils.inArray({ gesture: type, handler: handler }); if(index !== false) { self.eventHandlers.splice(index, 1); } }); return self; }, /** * trigger gesture event * @method trigger * @chainable * @param {String} gesture * @param {Object} [eventData] */ trigger: function triggerEvent(gesture, eventData) { // optional if(!eventData) { eventData = {}; } // create DOM event var event = Hammer.DOCUMENT.createEvent('Event'); event.initEvent(gesture, true, true); event.gesture = eventData; // trigger on the target if it is in the instance element, // this is for event delegation tricks var element = this.element; if(Utils.hasParent(eventData.target, element)) { element = eventData.target; } element.dispatchEvent(event); return this; }, /** * enable of disable hammer.js detection * @method enable * @chainable * @param {Boolean} state */ enable: function enable(state) { this.enabled = state; return this; }, /** * dispose this hammer instance * @method dispose * @return {Null} */ dispose: function dispose() { var i, eh; // undo all changes made by stop_browser_behavior Utils.toggleBehavior(this.element, this.options.behavior, false); // unbind all custom event handlers for(i = -1; (eh = this.eventHandlers[++i]);) { Utils.off(this.element, eh.gesture, eh.handler); } this.eventHandlers = []; // unbind the start event listener Event.off(this.element, EVENT_TYPES[EVENT_START], this.eventStartHandler); return null; } }; /** * @module gestures */ /** * Move with x fingers (default 1) around on the page. * Preventing the default browser behavior is a good way to improve feel and working. * ```` * hammertime.on("drag", function(ev) { * console.log(ev); * ev.gesture.preventDefault(); * }); * ```` * * @class Drag * @static */ /** * @event drag * @param {Object} ev */ /** * @event dragstart * @param {Object} ev */ /** * @event dragend * @param {Object} ev */ /** * @event drapleft * @param {Object} ev */ /** * @event dragright * @param {Object} ev */ /** * @event dragup * @param {Object} ev */ /** * @event dragdown * @param {Object} ev */ /** * @param {String} name */ (function(name) { var triggered = false; function dragGesture(ev, inst) { var cur = Detection.current; // max touches if(inst.options.dragMaxTouches > 0 && ev.touches.length > inst.options.dragMaxTouches) { return; } switch(ev.eventType) { case EVENT_START: triggered = false; break; case EVENT_MOVE: // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(ev.distance < inst.options.dragMinDistance && cur.name != name) { return; } var startCenter = cur.startEvent.center; // we are dragging! if(cur.name != name) { cur.name = name; if(inst.options.dragDistanceCorrection && ev.distance > 0) { // When a drag is triggered, set the event center to dragMinDistance pixels from the original event center. // Without this correction, the dragged distance would jumpstart at dragMinDistance pixels instead of at 0. // It might be useful to save the original start point somewhere var factor = Math.abs(inst.options.dragMinDistance / ev.distance); startCenter.pageX += ev.deltaX * factor; startCenter.pageY += ev.deltaY * factor; startCenter.clientX += ev.deltaX * factor; startCenter.clientY += ev.deltaY * factor; // recalculate event data using new start point ev = Detection.extendEventData(ev); } } // lock drag to axis? if(cur.lastEvent.dragLockToAxis || ( inst.options.dragLockToAxis && inst.options.dragLockMinDistance <= ev.distance )) { ev.dragLockToAxis = true; } // keep direction on the axis that the drag gesture started on var lastDirection = cur.lastEvent.direction; if(ev.dragLockToAxis && lastDirection !== ev.direction) { if(Utils.isVertical(lastDirection)) { ev.direction = (ev.deltaY < 0) ? DIRECTION_UP : DIRECTION_DOWN; } else { ev.direction = (ev.deltaX < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT; } } // first time, trigger dragstart event if(!triggered) { inst.trigger(name + 'start', ev); triggered = true; } // trigger events inst.trigger(name, ev); inst.trigger(name + ev.direction, ev); var isVertical = Utils.isVertical(ev.direction); // block the browser events if((inst.options.dragBlockVertical && isVertical) || (inst.options.dragBlockHorizontal && !isVertical)) { ev.preventDefault(); } break; case EVENT_RELEASE: if(triggered && ev.changedLength <= inst.options.dragMaxTouches) { inst.trigger(name + 'end', ev); triggered = false; } break; case EVENT_END: triggered = false; break; } } Hammer.gestures.Drag = { name: name, index: 50, handler: dragGesture, defaults: { /** * minimal movement that have to be made before the drag event gets triggered * @property dragMinDistance * @type {Number} * @default 10 */ dragMinDistance: 10, /** * Set dragDistanceCorrection to true to make the starting point of the drag * be calculated from where the drag was triggered, not from where the touch started. * Useful to avoid a jerk-starting drag, which can make fine-adjustments * through dragging difficult, and be visually unappealing. * @property dragDistanceCorrection * @type {Boolean} * @default true */ dragDistanceCorrection: true, /** * set 0 for unlimited, but this can conflict with transform * @property dragMaxTouches * @type {Number} * @default 1 */ dragMaxTouches: 1, /** * prevent default browser behavior when dragging occurs * be careful with it, it makes the element a blocking element * when you are using the drag gesture, it is a good practice to set this true * @property dragBlockHorizontal * @type {Boolean} * @default false */ dragBlockHorizontal: false, /** * same as `dragBlockHorizontal`, but for vertical movement * @property dragBlockVertical * @type {Boolean} * @default false */ dragBlockVertical: false, /** * dragLockToAxis keeps the drag gesture on the axis that it started on, * It disallows vertical directions if the initial direction was horizontal, and vice versa. * @property dragLockToAxis * @type {Boolean} * @default false */ dragLockToAxis: false, /** * drag lock only kicks in when distance > dragLockMinDistance * This way, locking occurs only when the distance has become large enough to reliably determine the direction * @property dragLockMinDistance * @type {Number} * @default 25 */ dragLockMinDistance: 25 } }; })('drag'); /** * @module gestures */ /** * trigger a simple gesture event, so you can do anything in your handler. * only usable if you know what your doing... * * @class Gesture * @static */ /** * @event gesture * @param {Object} ev */ Hammer.gestures.Gesture = { name: 'gesture', index: 1337, handler: function releaseGesture(ev, inst) { inst.trigger(this.name, ev); } }; /** * @module gestures */ /** * Touch stays at the same place for x time * * @class Hold * @static */ /** * @event hold * @param {Object} ev */ /** * @param {String} name */ (function(name) { var timer; function holdGesture(ev, inst) { var options = inst.options, current = Detection.current; switch(ev.eventType) { case EVENT_START: clearTimeout(timer); // set the gesture so we can check in the timeout if it still is current.name = name; // set timer and if after the timeout it still is hold, // we trigger the hold event timer = setTimeout(function() { if(current && current.name == name) { inst.trigger(name, ev); } }, options.holdTimeout); break; case EVENT_MOVE: if(ev.distance > options.holdThreshold) { clearTimeout(timer); } break; case EVENT_RELEASE: clearTimeout(timer); break; } } Hammer.gestures.Hold = { name: name, index: 10, defaults: { /** * @property holdTimeout * @type {Number} * @default 500 */ holdTimeout: 500, /** * movement allowed while holding * @property holdThreshold * @type {Number} * @default 2 */ holdThreshold: 2 }, handler: holdGesture }; })('hold'); /** * @module gestures */ /** * when a touch is being released from the page * * @class Release * @static */ /** * @event release * @param {Object} ev */ Hammer.gestures.Release = { name: 'release', index: Infinity, handler: function releaseGesture(ev, inst) { if(ev.eventType == EVENT_RELEASE) { inst.trigger(this.name, ev); } } }; /** * @module gestures */ /** * triggers swipe events when the end velocity is above the threshold * for best usage, set `preventDefault` (on the drag gesture) to `true` * ```` * hammertime.on("dragleft swipeleft", function(ev) { * console.log(ev); * ev.gesture.preventDefault(); * }); * ```` * * @class Swipe * @static */ /** * @event swipe * @param {Object} ev */ /** * @event swipeleft * @param {Object} ev */ /** * @event swiperight * @param {Object} ev */ /** * @event swipeup * @param {Object} ev */ /** * @event swipedown * @param {Object} ev */ Hammer.gestures.Swipe = { name: 'swipe', index: 40, defaults: { /** * @property swipeMinTouches * @type {Number} * @default 1 */ swipeMinTouches: 1, /** * @property swipeMaxTouches * @type {Number} * @default 1 */ swipeMaxTouches: 1, /** * horizontal swipe velocity * @property swipeVelocityX * @type {Number} * @default 0.6 */ swipeVelocityX: 0.6, /** * vertical swipe velocity * @property swipeVelocityY * @type {Number} * @default 0.6 */ swipeVelocityY: 0.6 }, handler: function swipeGesture(ev, inst) { if(ev.eventType == EVENT_RELEASE) { var touches = ev.touches.length, options = inst.options; // max touches if(touches < options.swipeMinTouches || touches > options.swipeMaxTouches) { return; } // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(ev.velocityX > options.swipeVelocityX || ev.velocityY > options.swipeVelocityY) { // trigger swipe events inst.trigger(this.name, ev); inst.trigger(this.name + ev.direction, ev); } } } }; /** * @module gestures */ /** * Single tap and a double tap on a place * * @class Tap * @static */ /** * @event tap * @param {Object} ev */ /** * @event doubletap * @param {Object} ev */ /** * @param {String} name */ (function(name) { var hasMoved = false; function tapGesture(ev, inst) { var options = inst.options, current = Detection.current, prev = Detection.previous, sincePrev, didDoubleTap; switch(ev.eventType) { case EVENT_START: hasMoved = false; break; case EVENT_MOVE: hasMoved = hasMoved || (ev.distance > options.tapMaxDistance); break; case EVENT_END: if(!Utils.inStr(ev.srcEvent.type, 'cancel') && ev.deltaTime < options.tapMaxTime && !hasMoved) { // previous gesture, for the double tap since these are two different gesture detections sincePrev = prev && prev.lastEvent && ev.timeStamp - prev.lastEvent.timeStamp; didDoubleTap = false; // check if double tap if(prev && prev.name == name && (sincePrev && sincePrev < options.doubleTapInterval) && ev.distance < options.doubleTapDistance) { inst.trigger('doubletap', ev); didDoubleTap = true; } // do a single tap if(!didDoubleTap || options.tapAlways) { current.name = name; inst.trigger(current.name, ev); } } break; } } Hammer.gestures.Tap = { name: name, index: 100, handler: tapGesture, defaults: { /** * max time of a tap, this is for the slow tappers * @property tapMaxTime * @type {Number} * @default 250 */ tapMaxTime: 250, /** * max distance of movement of a tap, this is for the slow tappers * @property tapMaxDistance * @type {Number} * @default 10 */ tapMaxDistance: 10, /** * always trigger the `tap` event, even while double-tapping * @property tapAlways * @type {Boolean} * @default true */ tapAlways: true, /** * max distance between two taps * @property doubleTapDistance * @type {Number} * @default 20 */ doubleTapDistance: 20, /** * max time between two taps * @property doubleTapInterval * @type {Number} * @default 300 */ doubleTapInterval: 300 } }; })('tap'); /** * @module gestures */ /** * when a touch is being touched at the page * * @class Touch * @static */ /** * @event touch * @param {Object} ev */ Hammer.gestures.Touch = { name: 'touch', index: -Infinity, defaults: { /** * call preventDefault at touchstart, and makes the element blocking by disabling the scrolling of the page, * but it improves gestures like transforming and dragging. * be careful with using this, it can be very annoying for users to be stuck on the page * @property preventDefault * @type {Boolean} * @default false */ preventDefault: false, /** * disable mouse events, so only touch (or pen!) input triggers events * @property preventMouse * @type {Boolean} * @default false */ preventMouse: false }, handler: function touchGesture(ev, inst) { if(inst.options.preventMouse && ev.pointerType == POINTER_MOUSE) { ev.stopDetect(); return; } if(inst.options.preventDefault) { ev.preventDefault(); } if(ev.eventType == EVENT_TOUCH) { inst.trigger('touch', ev); } } }; /** * @module gestures */ /** * User want to scale or rotate with 2 fingers * Preventing the default browser behavior is a good way to improve feel and working. This can be done with the * `preventDefault` option. * * @class Transform * @static */ /** * @event transform * @param {Object} ev */ /** * @event transformstart * @param {Object} ev */ /** * @event transformend * @param {Object} ev */ /** * @event pinchin * @param {Object} ev */ /** * @event pinchout * @param {Object} ev */ /** * @event rotate * @param {Object} ev */ /** * @param {String} name */ (function(name) { var triggered = false; function transformGesture(ev, inst) { switch(ev.eventType) { case EVENT_START: triggered = false; break; case EVENT_MOVE: // at least multitouch if(ev.touches.length < 2) { return; } var scaleThreshold = Math.abs(1 - ev.scale); var rotationThreshold = Math.abs(ev.rotation); // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(scaleThreshold < inst.options.transformMinScale && rotationThreshold < inst.options.transformMinRotation) { return; } // we are transforming! Detection.current.name = name; // first time, trigger dragstart event if(!triggered) { inst.trigger(name + 'start', ev); triggered = true; } inst.trigger(name, ev); // basic transform event // trigger rotate event if(rotationThreshold > inst.options.transformMinRotation) { inst.trigger('rotate', ev); } // trigger pinch event if(scaleThreshold > inst.options.transformMinScale) { inst.trigger('pinch', ev); inst.trigger('pinch' + (ev.scale < 1 ? 'in' : 'out'), ev); } break; case EVENT_RELEASE: if(triggered && ev.changedLength < 2) { inst.trigger(name + 'end', ev); triggered = false; } break; } } Hammer.gestures.Transform = { name: name, index: 45, defaults: { /** * minimal scale factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1 * @property transformMinScale * @type {Number} * @default 0.01 */ transformMinScale: 0.01, /** * rotation in degrees * @property transformMinRotation * @type {Number} * @default 1 */ transformMinRotation: 1 }, handler: transformGesture }; })('transform'); /** * @module hammer */ // AMD export if(true) { !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { return Hammer; }.call(exports, __webpack_require__, exports, module)), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); // commonjs export } else if(typeof module !== 'undefined' && module.exports) { module.exports = Hammer; // browser export } else { window.Hammer = Hammer; } })(window); /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { /** * Creation of the ClusterMixin var. * * This contains all the functions the Network object can use to employ clustering */ /** * This is only called in the constructor of the network object * */ exports.startWithClustering = function() { // cluster if the data set is big this.clusterToFit(this.constants.clustering.initialMaxNodes, true); // updates the lables after clustering this.updateLabels(); // this is called here because if clusterin is disabled, the start and stabilize are called in // the setData function. if (this.stabilize) { this._stabilize(); } this.start(); }; /** * This function clusters until the initialMaxNodes has been reached * * @param {Number} maxNumberOfNodes * @param {Boolean} reposition */ exports.clusterToFit = function(maxNumberOfNodes, reposition) { var numberOfNodes = this.nodeIndices.length; var maxLevels = 50; var level = 0; // we first cluster the hubs, then we pull in the outliers, repeat while (numberOfNodes > maxNumberOfNodes && level < maxLevels) { if (level % 3 == 0) { this.forceAggregateHubs(true); this.normalizeClusterLevels(); } else { this.increaseClusterLevel(); // this also includes a cluster normalization } numberOfNodes = this.nodeIndices.length; level += 1; } // after the clustering we reposition the nodes to reduce the initial chaos if (level > 0 && reposition == true) { this.repositionNodes(); } this._updateCalculationNodes(); }; /** * This function can be called to open up a specific cluster. It is only called by * It will unpack the cluster back one level. * * @param node | Node object: cluster to open. */ exports.openCluster = function(node) { var isMovingBeforeClustering = this.moving; if (node.clusterSize > this.constants.clustering.sectorThreshold && this._nodeInActiveArea(node) && !(this._sector() == "default" && this.nodeIndices.length == 1)) { // this loads a new sector, loads the nodes and edges and nodeIndices of it. this._addSector(node); var level = 0; // we decluster until we reach a decent number of nodes while ((this.nodeIndices.length < this.constants.clustering.initialMaxNodes) && (level < 10)) { this.decreaseClusterLevel(); level += 1; } } else { this._expandClusterNode(node,false,true); // update the index list, dynamic edges and labels this._updateNodeIndexList(); this._updateDynamicEdges(); this._updateCalculationNodes(); this.updateLabels(); } // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded if (this.moving != isMovingBeforeClustering) { this.start(); } }; /** * This calls the updateClustes with default arguments */ exports.updateClustersDefault = function() { if (this.constants.clustering.enabled == true) { this.updateClusters(0,false,false); } }; /** * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will * be clustered with their connected node. This can be repeated as many times as needed. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets. */ exports.increaseClusterLevel = function() { this.updateClusters(-1,false,true); }; /** * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will * be unpacked if they are a cluster. This can be repeated as many times as needed. * This can be called externally (by a key-bind for instance) to look into clusters without zooming. */ exports.decreaseClusterLevel = function() { this.updateClusters(1,false,true); }; /** * This is the main clustering function. It clusters and declusters on zoom or forced * This function clusters on zoom, it can be called with a predefined zoom direction * If out, check if we can form clusters, if in, check if we can open clusters. * This function is only called from _zoom() * * @param {Number} zoomDirection | -1 / 0 / +1 for zoomOut / determineByZoom / zoomIn * @param {Boolean} recursive | enabled or disable recursive calling of the opening of clusters * @param {Boolean} force | enabled or disable forcing * @param {Boolean} doNotStart | if true do not call start * */ exports.updateClusters = function(zoomDirection,recursive,force,doNotStart) { var isMovingBeforeClustering = this.moving; var amountOfNodes = this.nodeIndices.length; // on zoom out collapse the sector if the scale is at the level the sector was made if (this.previousScale > this.scale && zoomDirection == 0) { this._collapseSector(); } // check if we zoom in or out if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out // forming clusters when forced pulls outliers in. When not forced, the edge length of the // outer nodes determines if it is being clustered this._formClusters(force); } else if (this.previousScale < this.scale || zoomDirection == 1) { // zoom in if (force == true) { // _openClusters checks for each node if the formationScale of the cluster is smaller than // the current scale and if so, declusters. When forced, all clusters are reduced by one step this._openClusters(recursive,force); } else { // if a cluster takes up a set percentage of the active window this._openClustersBySize(); } } this._updateNodeIndexList(); // if a cluster was NOT formed and the user zoomed out, we try clustering by hubs if (this.nodeIndices.length == amountOfNodes && (this.previousScale > this.scale || zoomDirection == -1)) { this._aggregateHubs(force); this._updateNodeIndexList(); } // we now reduce chains. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out this.handleChains(); this._updateNodeIndexList(); } this.previousScale = this.scale; // rest of the update the index list, dynamic edges and labels this._updateDynamicEdges(); this.updateLabels(); // if a cluster was formed, we increase the clusterSession if (this.nodeIndices.length < amountOfNodes) { // this means a clustering operation has taken place this.clusterSession += 1; // if clusters have been made, we normalize the cluster level this.normalizeClusterLevels(); } if (doNotStart == false || doNotStart === undefined) { // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded if (this.moving != isMovingBeforeClustering) { this.start(); } } this._updateCalculationNodes(); }; /** * This function handles the chains. It is called on every updateClusters(). */ exports.handleChains = function() { // after clustering we check how many chains there are var chainPercentage = this._getChainFraction(); if (chainPercentage > this.constants.clustering.chainThreshold) { this._reduceAmountOfChains(1 - this.constants.clustering.chainThreshold / chainPercentage) } }; /** * this functions starts clustering by hubs * The minimum hub threshold is set globally * * @private */ exports._aggregateHubs = function(force) { this._getHubSize(); this._formClustersByHub(force,false); }; /** * This function is fired by keypress. It forces hubs to form. * */ exports.forceAggregateHubs = function(doNotStart) { var isMovingBeforeClustering = this.moving; var amountOfNodes = this.nodeIndices.length; this._aggregateHubs(true); // update the index list, dynamic edges and labels this._updateNodeIndexList(); this._updateDynamicEdges(); this.updateLabels(); // if a cluster was formed, we increase the clusterSession if (this.nodeIndices.length != amountOfNodes) { this.clusterSession += 1; } if (doNotStart == false || doNotStart === undefined) { // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded if (this.moving != isMovingBeforeClustering) { this.start(); } } }; /** * If a cluster takes up more than a set percentage of the screen, open the cluster * * @private */ exports._openClustersBySize = function() { for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { var node = this.nodes[nodeId]; if (node.inView() == true) { if ((node.width*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) || (node.height*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) { this.openCluster(node); } } } } }; /** * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it * has to be opened based on the current zoom level. * * @private */ exports._openClusters = function(recursive,force) { for (var i = 0; i < this.nodeIndices.length; i++) { var node = this.nodes[this.nodeIndices[i]]; this._expandClusterNode(node,recursive,force); this._updateCalculationNodes(); } }; /** * This function checks if a node has to be opened. This is done by checking the zoom level. * If the node contains child nodes, this function is recursively called on the child nodes as well. * This recursive behaviour is optional and can be set by the recursive argument. * * @param {Node} parentNode | to check for cluster and expand * @param {Boolean} recursive | enabled or disable recursive calling * @param {Boolean} force | enabled or disable forcing * @param {Boolean} [openAll] | This will recursively force all nodes in the parent to be released * @private */ exports._expandClusterNode = function(parentNode, recursive, force, openAll) { // first check if node is a cluster if (parentNode.clusterSize > 1) { // this means that on a double tap event or a zoom event, the cluster fully unpacks if it is smaller than 20 if (parentNode.clusterSize < this.constants.clustering.sectorThreshold) { openAll = true; } recursive = openAll ? true : recursive; // if the last child has been added on a smaller scale than current scale decluster if (parentNode.formationScale < this.scale || force == true) { // we will check if any of the contained child nodes should be removed from the cluster for (var containedNodeId in parentNode.containedNodes) { if (parentNode.containedNodes.hasOwnProperty(containedNodeId)) { var childNode = parentNode.containedNodes[containedNodeId]; // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that // the largest cluster is the one that comes from outside if (force == true) { if (childNode.clusterSession == parentNode.clusterSessions[parentNode.clusterSessions.length-1] || openAll) { this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll); } } else { if (this._nodeInActiveArea(parentNode)) { this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll); } } } } } } }; /** * ONLY CALLED FROM _expandClusterNode * * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove * the child node from the parent contained_node object and put it back into the global nodes object. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object. * * @param {Node} parentNode | the parent node * @param {String} containedNodeId | child_node id as it is contained in the containedNodes object of the parent node * @param {Boolean} recursive | This will also check if the child needs to be expanded. * With force and recursive both true, the entire cluster is unpacked * @param {Boolean} force | This will disregard the zoom level and will expel this child from the parent * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released * @private */ exports._expelChildFromParent = function(parentNode, containedNodeId, recursive, force, openAll) { var childNode = parentNode.containedNodes[containedNodeId]; // if child node has been added on smaller scale than current, kick out if (childNode.formationScale < this.scale || force == true) { // unselect all selected items this._unselectAll(); // put the child node back in the global nodes object this.nodes[containedNodeId] = childNode; // release the contained edges from this childNode back into the global edges this._releaseContainedEdges(parentNode,childNode); // reconnect rerouted edges to the childNode this._connectEdgeBackToChild(parentNode,childNode); // validate all edges in dynamicEdges this._validateEdges(parentNode); // undo the changes from the clustering operation on the parent node parentNode.options.mass -= childNode.options.mass; parentNode.clusterSize -= childNode.clusterSize; parentNode.options.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize); parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length; // place the child node near the parent, not at the exact same location to avoid chaos in the system childNode.x = parentNode.x + parentNode.growthIndicator * (0.5 - Math.random()); childNode.y = parentNode.y + parentNode.growthIndicator * (0.5 - Math.random()); // remove node from the list delete parentNode.containedNodes[containedNodeId]; // check if there are other childs with this clusterSession in the parent. var othersPresent = false; for (var childNodeId in parentNode.containedNodes) { if (parentNode.containedNodes.hasOwnProperty(childNodeId)) { if (parentNode.containedNodes[childNodeId].clusterSession == childNode.clusterSession) { othersPresent = true; break; } } } // if there are no others, remove the cluster session from the list if (othersPresent == false) { parentNode.clusterSessions.pop(); } this._repositionBezierNodes(childNode); // this._repositionBezierNodes(parentNode); // remove the clusterSession from the child node childNode.clusterSession = 0; // recalculate the size of the node on the next time the node is rendered parentNode.clearSizeCache(); // restart the simulation to reorganise all nodes this.moving = true; } // check if a further expansion step is possible if recursivity is enabled if (recursive == true) { this._expandClusterNode(childNode,recursive,force,openAll); } }; /** * position the bezier nodes at the center of the edges * * @param node * @private */ exports._repositionBezierNodes = function(node) { for (var i = 0; i < node.dynamicEdges.length; i++) { node.dynamicEdges[i].positionBezierNode(); } }; /** * This function checks if any nodes at the end of their trees have edges below a threshold length * This function is called only from updateClusters() * forceLevelCollapse ignores the length of the edge and collapses one level * This means that a node with only one edge will be clustered with its connected node * * @private * @param {Boolean} force */ exports._formClusters = function(force) { if (force == false) { this._formClustersByZoom(); } else { this._forceClustersByZoom(); } }; /** * This function handles the clustering by zooming out, this is based on a minimum edge distance * * @private */ exports._formClustersByZoom = function() { var dx,dy,length, minLength = this.constants.clustering.clusterEdgeThreshold/this.scale; // check if any edges are shorter than minLength and start the clustering // the clustering favours the node with the larger mass for (var edgeId in this.edges) { if (this.edges.hasOwnProperty(edgeId)) { var edge = this.edges[edgeId]; if (edge.connected) { if (edge.toId != edge.fromId) { dx = (edge.to.x - edge.from.x); dy = (edge.to.y - edge.from.y); length = Math.sqrt(dx * dx + dy * dy); if (length < minLength) { // first check which node is larger var parentNode = edge.from; var childNode = edge.to; if (edge.to.options.mass > edge.from.options.mass) { parentNode = edge.to; childNode = edge.from; } if (childNode.dynamicEdgesLength == 1) { this._addToCluster(parentNode,childNode,false); } else if (parentNode.dynamicEdgesLength == 1) { this._addToCluster(childNode,parentNode,false); } } } } } } }; /** * This function forces the network to cluster all nodes with only one connecting edge to their * connected node. * * @private */ exports._forceClustersByZoom = function() { for (var nodeId in this.nodes) { // another node could have absorbed this child. if (this.nodes.hasOwnProperty(nodeId)) { var childNode = this.nodes[nodeId]; // the edges can be swallowed by another decrease if (childNode.dynamicEdgesLength == 1 && childNode.dynamicEdges.length != 0) { var edge = childNode.dynamicEdges[0]; var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId]; // group to the largest node if (childNode.id != parentNode.id) { if (parentNode.options.mass > childNode.options.mass) { this._addToCluster(parentNode,childNode,true); } else { this._addToCluster(childNode,parentNode,true); } } } } } }; /** * To keep the nodes of roughly equal size we normalize the cluster levels. * This function clusters a node to its smallest connected neighbour. * * @param node * @private */ exports._clusterToSmallestNeighbour = function(node) { var smallestNeighbour = -1; var smallestNeighbourNode = null; for (var i = 0; i < node.dynamicEdges.length; i++) { if (node.dynamicEdges[i] !== undefined) { var neighbour = null; if (node.dynamicEdges[i].fromId != node.id) { neighbour = node.dynamicEdges[i].from; } else if (node.dynamicEdges[i].toId != node.id) { neighbour = node.dynamicEdges[i].to; } if (neighbour != null && smallestNeighbour > neighbour.clusterSessions.length) { smallestNeighbour = neighbour.clusterSessions.length; smallestNeighbourNode = neighbour; } } } if (neighbour != null && this.nodes[neighbour.id] !== undefined) { this._addToCluster(neighbour, node, true); } }; /** * This function forms clusters from hubs, it loops over all nodes * * @param {Boolean} force | Disregard zoom level * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges * @private */ exports._formClustersByHub = function(force, onlyEqual) { // we loop over all nodes in the list for (var nodeId in this.nodes) { // we check if it is still available since it can be used by the clustering in this loop if (this.nodes.hasOwnProperty(nodeId)) { this._formClusterFromHub(this.nodes[nodeId],force,onlyEqual); } } }; /** * This function forms a cluster from a specific preselected hub node * * @param {Node} hubNode | the node we will cluster as a hub * @param {Boolean} force | Disregard zoom level * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges * @param {Number} [absorptionSizeOffset] | * @private */ exports._formClusterFromHub = function(hubNode, force, onlyEqual, absorptionSizeOffset) { if (absorptionSizeOffset === undefined) { absorptionSizeOffset = 0; } // we decide if the node is a hub if ((hubNode.dynamicEdgesLength >= this.hubThreshold && onlyEqual == false) || (hubNode.dynamicEdgesLength == this.hubThreshold && onlyEqual == true)) { // initialize variables var dx,dy,length; var minLength = this.constants.clustering.clusterEdgeThreshold/this.scale; var allowCluster = false; // we create a list of edges because the dynamicEdges change over the course of this loop var edgesIdarray = []; var amountOfInitialEdges = hubNode.dynamicEdges.length; for (var j = 0; j < amountOfInitialEdges; j++) { edgesIdarray.push(hubNode.dynamicEdges[j].id); } // if the hub clustering is not forces, we check if one of the edges connected // to a cluster is small enough based on the constants.clustering.clusterEdgeThreshold if (force == false) { allowCluster = false; for (j = 0; j < amountOfInitialEdges; j++) { var edge = this.edges[edgesIdarray[j]]; if (edge !== undefined) { if (edge.connected) { if (edge.toId != edge.fromId) { dx = (edge.to.x - edge.from.x); dy = (edge.to.y - edge.from.y); length = Math.sqrt(dx * dx + dy * dy); if (length < minLength) { allowCluster = true; break; } } } } } } // start the clustering if allowed if ((!force && allowCluster) || force) { // we loop over all edges INITIALLY connected to this hub for (j = 0; j < amountOfInitialEdges; j++) { edge = this.edges[edgesIdarray[j]]; // the edge can be clustered by this function in a previous loop if (edge !== undefined) { var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId]; // we do not want hubs to merge with other hubs nor do we want to cluster itself. if ((childNode.dynamicEdges.length <= (this.hubThreshold + absorptionSizeOffset)) && (childNode.id != hubNode.id)) { this._addToCluster(hubNode,childNode,force); } } } } } }; /** * This function adds the child node to the parent node, creating a cluster if it is not already. * * @param {Node} parentNode | this is the node that will house the child node * @param {Node} childNode | this node will be deleted from the global this.nodes and stored in the parent node * @param {Boolean} force | true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse * @private */ exports._addToCluster = function(parentNode, childNode, force) { // join child node in the parent node parentNode.containedNodes[childNode.id] = childNode; // manage all the edges connected to the child and parent nodes for (var i = 0; i < childNode.dynamicEdges.length; i++) { var edge = childNode.dynamicEdges[i]; if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode this._addToContainedEdges(parentNode,childNode,edge); } else { this._connectEdgeToCluster(parentNode,childNode,edge); } } // a contained node has no dynamic edges. childNode.dynamicEdges = []; // remove circular edges from clusters this._containCircularEdgesFromNode(parentNode,childNode); // remove the childNode from the global nodes object delete this.nodes[childNode.id]; // update the properties of the child and parent var massBefore = parentNode.options.mass; childNode.clusterSession = this.clusterSession; parentNode.options.mass += childNode.options.mass; parentNode.clusterSize += childNode.clusterSize; parentNode.options.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize); // keep track of the clustersessions so we can open the cluster up as it has been formed. if (parentNode.clusterSessions[parentNode.clusterSessions.length - 1] != this.clusterSession) { parentNode.clusterSessions.push(this.clusterSession); } // forced clusters only open from screen size and double tap if (force == true) { // parentNode.formationScale = Math.pow(1 - (1.0/11.0),this.clusterSession+3); parentNode.formationScale = 0; } else { parentNode.formationScale = this.scale; // The latest child has been added on this scale } // recalculate the size of the node on the next time the node is rendered parentNode.clearSizeCache(); // set the pop-out scale for the childnode parentNode.containedNodes[childNode.id].formationScale = parentNode.formationScale; // nullify the movement velocity of the child, this is to avoid hectic behaviour childNode.clearVelocity(); // the mass has altered, preservation of energy dictates the velocity to be updated parentNode.updateVelocity(massBefore); // restart the simulation to reorganise all nodes this.moving = true; }; /** * This function will apply the changes made to the remainingEdges during the formation of the clusters. * This is a seperate function to allow for level-wise collapsing of the node barnesHutTree. * It has to be called if a level is collapsed. It is called by _formClusters(). * @private */ exports._updateDynamicEdges = function() { for (var i = 0; i < this.nodeIndices.length; i++) { var node = this.nodes[this.nodeIndices[i]]; node.dynamicEdgesLength = node.dynamicEdges.length; // this corrects for multiple edges pointing at the same other node var correction = 0; if (node.dynamicEdgesLength > 1) { for (var j = 0; j < node.dynamicEdgesLength - 1; j++) { var edgeToId = node.dynamicEdges[j].toId; var edgeFromId = node.dynamicEdges[j].fromId; for (var k = j+1; k < node.dynamicEdgesLength; k++) { if ((node.dynamicEdges[k].toId == edgeToId && node.dynamicEdges[k].fromId == edgeFromId) || (node.dynamicEdges[k].fromId == edgeToId && node.dynamicEdges[k].toId == edgeFromId)) { correction += 1; } } } } node.dynamicEdgesLength -= correction; } }; /** * This adds an edge from the childNode to the contained edges of the parent node * * @param parentNode | Node object * @param childNode | Node object * @param edge | Edge object * @private */ exports._addToContainedEdges = function(parentNode, childNode, edge) { // create an array object if it does not yet exist for this childNode if (!(parentNode.containedEdges.hasOwnProperty(childNode.id))) { parentNode.containedEdges[childNode.id] = [] } // add this edge to the list parentNode.containedEdges[childNode.id].push(edge); // remove the edge from the global edges object delete this.edges[edge.id]; // remove the edge from the parent object for (var i = 0; i < parentNode.dynamicEdges.length; i++) { if (parentNode.dynamicEdges[i].id == edge.id) { parentNode.dynamicEdges.splice(i,1); break; } } }; /** * This function connects an edge that was connected to a child node to the parent node. * It keeps track of which nodes it has been connected to with the originalId array. * * @param {Node} parentNode | Node object * @param {Node} childNode | Node object * @param {Edge} edge | Edge object * @private */ exports._connectEdgeToCluster = function(parentNode, childNode, edge) { // handle circular edges if (edge.toId == edge.fromId) { this._addToContainedEdges(parentNode, childNode, edge); } else { if (edge.toId == childNode.id) { // edge connected to other node on the "to" side edge.originalToId.push(childNode.id); edge.to = parentNode; edge.toId = parentNode.id; } else { // edge connected to other node with the "from" side edge.originalFromId.push(childNode.id); edge.from = parentNode; edge.fromId = parentNode.id; } this._addToReroutedEdges(parentNode,childNode,edge); } }; /** * If a node is connected to itself, a circular edge is drawn. When clustering we want to contain * these edges inside of the cluster. * * @param parentNode * @param childNode * @private */ exports._containCircularEdgesFromNode = function(parentNode, childNode) { // manage all the edges connected to the child and parent nodes for (var i = 0; i < parentNode.dynamicEdges.length; i++) { var edge = parentNode.dynamicEdges[i]; // handle circular edges if (edge.toId == edge.fromId) { this._addToContainedEdges(parentNode, childNode, edge); } } }; /** * This adds an edge from the childNode to the rerouted edges of the parent node * * @param parentNode | Node object * @param childNode | Node object * @param edge | Edge object * @private */ exports._addToReroutedEdges = function(parentNode, childNode, edge) { // create an array object if it does not yet exist for this childNode // we store the edge in the rerouted edges so we can restore it when the cluster pops open if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) { parentNode.reroutedEdges[childNode.id] = []; } parentNode.reroutedEdges[childNode.id].push(edge); // this edge becomes part of the dynamicEdges of the cluster node parentNode.dynamicEdges.push(edge); }; /** * This function connects an edge that was connected to a cluster node back to the child node. * * @param parentNode | Node object * @param childNode | Node object * @private */ exports._connectEdgeBackToChild = function(parentNode, childNode) { if (parentNode.reroutedEdges.hasOwnProperty(childNode.id)) { for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) { var edge = parentNode.reroutedEdges[childNode.id][i]; if (edge.originalFromId[edge.originalFromId.length-1] == childNode.id) { edge.originalFromId.pop(); edge.fromId = childNode.id; edge.from = childNode; } else { edge.originalToId.pop(); edge.toId = childNode.id; edge.to = childNode; } // append this edge to the list of edges connecting to the childnode childNode.dynamicEdges.push(edge); // remove the edge from the parent object for (var j = 0; j < parentNode.dynamicEdges.length; j++) { if (parentNode.dynamicEdges[j].id == edge.id) { parentNode.dynamicEdges.splice(j,1); break; } } } // remove the entry from the rerouted edges delete parentNode.reroutedEdges[childNode.id]; } }; /** * When loops are clustered, an edge can be both in the rerouted array and the contained array. * This function is called last to verify that all edges in dynamicEdges are in fact connected to the * parentNode * * @param parentNode | Node object * @private */ exports._validateEdges = function(parentNode) { for (var i = 0; i < parentNode.dynamicEdges.length; i++) { var edge = parentNode.dynamicEdges[i]; if (parentNode.id != edge.toId && parentNode.id != edge.fromId) { parentNode.dynamicEdges.splice(i,1); } } }; /** * This function released the contained edges back into the global domain and puts them back into the * dynamic edges of both parent and child. * * @param {Node} parentNode | * @param {Node} childNode | * @private */ exports._releaseContainedEdges = function(parentNode, childNode) { for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) { var edge = parentNode.containedEdges[childNode.id][i]; // put the edge back in the global edges object this.edges[edge.id] = edge; // put the edge back in the dynamic edges of the child and parent childNode.dynamicEdges.push(edge); parentNode.dynamicEdges.push(edge); } // remove the entry from the contained edges delete parentNode.containedEdges[childNode.id]; }; // ------------------- UTILITY FUNCTIONS ---------------------------- // /** * This updates the node labels for all nodes (for debugging purposes) */ exports.updateLabels = function() { var nodeId; // update node labels for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { var node = this.nodes[nodeId]; if (node.clusterSize > 1) { node.label = "[".concat(String(node.clusterSize),"]"); } } } // update node labels for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; if (node.clusterSize == 1) { if (node.originalLabel !== undefined) { node.label = node.originalLabel; } else { node.label = String(node.id); } } } } // /* Debug Override */ // for (nodeId in this.nodes) { // if (this.nodes.hasOwnProperty(nodeId)) { // node = this.nodes[nodeId]; // node.label = String(node.level); // } // } }; /** * We want to keep the cluster level distribution rather small. This means we do not want unclustered nodes * if the rest of the nodes are already a few cluster levels in. * To fix this we use this function. It determines the min and max cluster level and sends nodes that have not * clustered enough to the clusterToSmallestNeighbours function. */ exports.normalizeClusterLevels = function() { var maxLevel = 0; var minLevel = 1e9; var clusterLevel = 0; var nodeId; // we loop over all nodes in the list for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { clusterLevel = this.nodes[nodeId].clusterSessions.length; if (maxLevel < clusterLevel) {maxLevel = clusterLevel;} if (minLevel > clusterLevel) {minLevel = clusterLevel;} } } if (maxLevel - minLevel > this.constants.clustering.clusterLevelDifference) { var amountOfNodes = this.nodeIndices.length; var targetLevel = maxLevel - this.constants.clustering.clusterLevelDifference; // we loop over all nodes in the list for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { if (this.nodes[nodeId].clusterSessions.length < targetLevel) { this._clusterToSmallestNeighbour(this.nodes[nodeId]); } } } this._updateNodeIndexList(); this._updateDynamicEdges(); // if a cluster was formed, we increase the clusterSession if (this.nodeIndices.length != amountOfNodes) { this.clusterSession += 1; } } }; /** * This function determines if the cluster we want to decluster is in the active area * this means around the zoom center * * @param {Node} node * @returns {boolean} * @private */ exports._nodeInActiveArea = function(node) { return ( Math.abs(node.x - this.areaCenter.x) <= this.constants.clustering.activeAreaBoxSize/this.scale && Math.abs(node.y - this.areaCenter.y) <= this.constants.clustering.activeAreaBoxSize/this.scale ) }; /** * This is an adaptation of the original repositioning function. This is called if the system is clustered initially * It puts large clusters away from the center and randomizes the order. * */ exports.repositionNodes = function() { for (var i = 0; i < this.nodeIndices.length; i++) { var node = this.nodes[this.nodeIndices[i]]; if ((node.xFixed == false || node.yFixed == false)) { var radius = 10 * 0.1*this.nodeIndices.length * Math.min(100,node.options.mass); var angle = 2 * Math.PI * Math.random(); if (node.xFixed == false) {node.x = radius * Math.cos(angle);} if (node.yFixed == false) {node.y = radius * Math.sin(angle);} this._repositionBezierNodes(node); } } }; /** * We determine how many connections denote an important hub. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%) * * @private */ exports._getHubSize = function() { var average = 0; var averageSquared = 0; var hubCounter = 0; var largestHub = 0; for (var i = 0; i < this.nodeIndices.length; i++) { var node = this.nodes[this.nodeIndices[i]]; if (node.dynamicEdgesLength > largestHub) { largestHub = node.dynamicEdgesLength; } average += node.dynamicEdgesLength; averageSquared += Math.pow(node.dynamicEdgesLength,2); hubCounter += 1; } average = average / hubCounter; averageSquared = averageSquared / hubCounter; var variance = averageSquared - Math.pow(average,2); var standardDeviation = Math.sqrt(variance); this.hubThreshold = Math.floor(average + 2*standardDeviation); // always have at least one to cluster if (this.hubThreshold > largestHub) { this.hubThreshold = largestHub; } // console.log("average",average,"averageSQ",averageSquared,"var",variance,"std",standardDeviation); // console.log("hubThreshold:",this.hubThreshold); }; /** * We reduce the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods * with this amount we can cluster specifically on these chains. * * @param {Number} fraction | between 0 and 1, the percentage of chains to reduce * @private */ exports._reduceAmountOfChains = function(fraction) { this.hubThreshold = 2; var reduceAmount = Math.floor(this.nodeIndices.length * fraction); for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) { if (reduceAmount > 0) { this._formClusterFromHub(this.nodes[nodeId],true,true,1); reduceAmount -= 1; } } } } }; /** * We get the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods * with this amount we can cluster specifically on these chains. * * @private */ exports._getChainFraction = function() { var chains = 0; var total = 0; for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) { chains += 1; } total += 1; } } return chains/total; }; /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); /** * Creation of the SectorMixin var. * * This contains all the functions the Network object can use to employ the sector system. * The sector system is always used by Network, though the benefits only apply to the use of clustering. * If clustering is not used, there is no overhead except for a duplicate object with references to nodes and edges. */ /** * This function is only called by the setData function of the Network object. * This loads the global references into the active sector. This initializes the sector. * * @private */ exports._putDataInSector = function() { this.sectors["active"][this._sector()].nodes = this.nodes; this.sectors["active"][this._sector()].edges = this.edges; this.sectors["active"][this._sector()].nodeIndices = this.nodeIndices; }; /** * /** * This function sets the global references to nodes, edges and nodeIndices back to * those of the supplied (active) sector. If a type is defined, do the specific type * * @param {String} sectorId * @param {String} [sectorType] | "active" or "frozen" * @private */ exports._switchToSector = function(sectorId, sectorType) { if (sectorType === undefined || sectorType == "active") { this._switchToActiveSector(sectorId); } else { this._switchToFrozenSector(sectorId); } }; /** * This function sets the global references to nodes, edges and nodeIndices back to * those of the supplied active sector. * * @param sectorId * @private */ exports._switchToActiveSector = function(sectorId) { this.nodeIndices = this.sectors["active"][sectorId]["nodeIndices"]; this.nodes = this.sectors["active"][sectorId]["nodes"]; this.edges = this.sectors["active"][sectorId]["edges"]; }; /** * This function sets the global references to nodes, edges and nodeIndices back to * those of the supplied active sector. * * @private */ exports._switchToSupportSector = function() { this.nodeIndices = this.sectors["support"]["nodeIndices"]; this.nodes = this.sectors["support"]["nodes"]; this.edges = this.sectors["support"]["edges"]; }; /** * This function sets the global references to nodes, edges and nodeIndices back to * those of the supplied frozen sector. * * @param sectorId * @private */ exports._switchToFrozenSector = function(sectorId) { this.nodeIndices = this.sectors["frozen"][sectorId]["nodeIndices"]; this.nodes = this.sectors["frozen"][sectorId]["nodes"]; this.edges = this.sectors["frozen"][sectorId]["edges"]; }; /** * This function sets the global references to nodes, edges and nodeIndices back to * those of the currently active sector. * * @private */ exports._loadLatestSector = function() { this._switchToSector(this._sector()); }; /** * This function returns the currently active sector Id * * @returns {String} * @private */ exports._sector = function() { return this.activeSector[this.activeSector.length-1]; }; /** * This function returns the previously active sector Id * * @returns {String} * @private */ exports._previousSector = function() { if (this.activeSector.length > 1) { return this.activeSector[this.activeSector.length-2]; } else { throw new TypeError('there are not enough sectors in the this.activeSector array.'); } }; /** * We add the active sector at the end of the this.activeSector array * This ensures it is the currently active sector returned by _sector() and it reaches the top * of the activeSector stack. When we reverse our steps we move from the end to the beginning of this stack. * * @param newId * @private */ exports._setActiveSector = function(newId) { this.activeSector.push(newId); }; /** * We remove the currently active sector id from the active sector stack. This happens when * we reactivate the previously active sector * * @private */ exports._forgetLastSector = function() { this.activeSector.pop(); }; /** * This function creates a new active sector with the supplied newId. This newId * is the expanding node id. * * @param {String} newId | Id of the new active sector * @private */ exports._createNewSector = function(newId) { // create the new sector this.sectors["active"][newId] = {"nodes":{}, "edges":{}, "nodeIndices":[], "formationScale": this.scale, "drawingNode": undefined}; // create the new sector render node. This gives visual feedback that you are in a new sector. this.sectors["active"][newId]['drawingNode'] = new Node( {id:newId, color: { background: "#eaefef", border: "495c5e" } },{},{},this.constants); this.sectors["active"][newId]['drawingNode'].clusterSize = 2; }; /** * This function removes the currently active sector. This is called when we create a new * active sector. * * @param {String} sectorId | Id of the active sector that will be removed * @private */ exports._deleteActiveSector = function(sectorId) { delete this.sectors["active"][sectorId]; }; /** * This function removes the currently active sector. This is called when we reactivate * the previously active sector. * * @param {String} sectorId | Id of the active sector that will be removed * @private */ exports._deleteFrozenSector = function(sectorId) { delete this.sectors["frozen"][sectorId]; }; /** * Freezing an active sector means moving it from the "active" object to the "frozen" object. * We copy the references, then delete the active entree. * * @param sectorId * @private */ exports._freezeSector = function(sectorId) { // we move the set references from the active to the frozen stack. this.sectors["frozen"][sectorId] = this.sectors["active"][sectorId]; // we have moved the sector data into the frozen set, we now remove it from the active set this._deleteActiveSector(sectorId); }; /** * This is the reverse operation of _freezeSector. Activating means moving the sector from the "frozen" * object to the "active" object. * * @param sectorId * @private */ exports._activateSector = function(sectorId) { // we move the set references from the frozen to the active stack. this.sectors["active"][sectorId] = this.sectors["frozen"][sectorId]; // we have moved the sector data into the active set, we now remove it from the frozen stack this._deleteFrozenSector(sectorId); }; /** * This function merges the data from the currently active sector with a frozen sector. This is used * in the process of reverting back to the previously active sector. * The data that is placed in the frozen (the previously active) sector is the node that has been removed from it * upon the creation of a new active sector. * * @param sectorId * @private */ exports._mergeThisWithFrozen = function(sectorId) { // copy all nodes for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { this.sectors["frozen"][sectorId]["nodes"][nodeId] = this.nodes[nodeId]; } } // copy all edges (if not fully clustered, else there are no edges) for (var edgeId in this.edges) { if (this.edges.hasOwnProperty(edgeId)) { this.sectors["frozen"][sectorId]["edges"][edgeId] = this.edges[edgeId]; } } // merge the nodeIndices for (var i = 0; i < this.nodeIndices.length; i++) { this.sectors["frozen"][sectorId]["nodeIndices"].push(this.nodeIndices[i]); } }; /** * This clusters the sector to one cluster. It was a single cluster before this process started so * we revert to that state. The clusterToFit function with a maximum size of 1 node does this. * * @private */ exports._collapseThisToSingleCluster = function() { this.clusterToFit(1,false); }; /** * We create a new active sector from the node that we want to open. * * @param node * @private */ exports._addSector = function(node) { // this is the currently active sector var sector = this._sector(); // // this should allow me to select nodes from a frozen set. // if (this.sectors['active'][sector]["nodes"].hasOwnProperty(node.id)) { // console.log("the node is part of the active sector"); // } // else { // console.log("I dont know what the fuck happened!!"); // } // when we switch to a new sector, we remove the node that will be expanded from the current nodes list. delete this.nodes[node.id]; var unqiueIdentifier = util.randomUUID(); // we fully freeze the currently active sector this._freezeSector(sector); // we create a new active sector. This sector has the Id of the node to ensure uniqueness this._createNewSector(unqiueIdentifier); // we add the active sector to the sectors array to be able to revert these steps later on this._setActiveSector(unqiueIdentifier); // we redirect the global references to the new sector's references. this._sector() now returns unqiueIdentifier this._switchToSector(this._sector()); // finally we add the node we removed from our previous active sector to the new active sector this.nodes[node.id] = node; }; /** * We close the sector that is currently open and revert back to the one before. * If the active sector is the "default" sector, nothing happens. * * @private */ exports._collapseSector = function() { // the currently active sector var sector = this._sector(); // we cannot collapse the default sector if (sector != "default") { if ((this.nodeIndices.length == 1) || (this.sectors["active"][sector]["drawingNode"].width*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) || (this.sectors["active"][sector]["drawingNode"].height*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) { var previousSector = this._previousSector(); // we collapse the sector back to a single cluster this._collapseThisToSingleCluster(); // we move the remaining nodes, edges and nodeIndices to the previous sector. // This previous sector is the one we will reactivate this._mergeThisWithFrozen(previousSector); // the previously active (frozen) sector now has all the data from the currently active sector. // we can now delete the active sector. this._deleteActiveSector(sector); // we activate the previously active (and currently frozen) sector. this._activateSector(previousSector); // we load the references from the newly active sector into the global references this._switchToSector(previousSector); // we forget the previously active sector because we reverted to the one before this._forgetLastSector(); // finally, we update the node index list. this._updateNodeIndexList(); // we refresh the list with calulation nodes and calculation node indices. this._updateCalculationNodes(); } } }; /** * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation(). * * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors * | we dont pass the function itself because then the "this" is the window object * | instead of the Network object * @param {*} [argument] | Optional: arguments to pass to the runFunction * @private */ exports._doInAllActiveSectors = function(runFunction,argument) { if (argument === undefined) { for (var sector in this.sectors["active"]) { if (this.sectors["active"].hasOwnProperty(sector)) { // switch the global references to those of this sector this._switchToActiveSector(sector); this[runFunction](); } } } else { for (var sector in this.sectors["active"]) { if (this.sectors["active"].hasOwnProperty(sector)) { // switch the global references to those of this sector this._switchToActiveSector(sector); var args = Array.prototype.splice.call(arguments, 1); if (args.length > 1) { this[runFunction](args[0],args[1]); } else { this[runFunction](argument); } } } } // we revert the global references back to our active sector this._loadLatestSector(); }; /** * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation(). * * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors * | we dont pass the function itself because then the "this" is the window object * | instead of the Network object * @param {*} [argument] | Optional: arguments to pass to the runFunction * @private */ exports._doInSupportSector = function(runFunction,argument) { if (argument === undefined) { this._switchToSupportSector(); this[runFunction](); } else { this._switchToSupportSector(); var args = Array.prototype.splice.call(arguments, 1); if (args.length > 1) { this[runFunction](args[0],args[1]); } else { this[runFunction](argument); } } // we revert the global references back to our active sector this._loadLatestSector(); }; /** * This runs a function in all frozen sectors. This is used in the _redraw(). * * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors * | we don't pass the function itself because then the "this" is the window object * | instead of the Network object * @param {*} [argument] | Optional: arguments to pass to the runFunction * @private */ exports._doInAllFrozenSectors = function(runFunction,argument) { if (argument === undefined) { for (var sector in this.sectors["frozen"]) { if (this.sectors["frozen"].hasOwnProperty(sector)) { // switch the global references to those of this sector this._switchToFrozenSector(sector); this[runFunction](); } } } else { for (var sector in this.sectors["frozen"]) { if (this.sectors["frozen"].hasOwnProperty(sector)) { // switch the global references to those of this sector this._switchToFrozenSector(sector); var args = Array.prototype.splice.call(arguments, 1); if (args.length > 1) { this[runFunction](args[0],args[1]); } else { this[runFunction](argument); } } } } this._loadLatestSector(); }; /** * This runs a function in all sectors. This is used in the _redraw(). * * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors * | we don't pass the function itself because then the "this" is the window object * | instead of the Network object * @param {*} [argument] | Optional: arguments to pass to the runFunction * @private */ exports._doInAllSectors = function(runFunction,argument) { var args = Array.prototype.splice.call(arguments, 1); if (argument === undefined) { this._doInAllActiveSectors(runFunction); this._doInAllFrozenSectors(runFunction); } else { if (args.length > 1) { this._doInAllActiveSectors(runFunction,args[0],args[1]); this._doInAllFrozenSectors(runFunction,args[0],args[1]); } else { this._doInAllActiveSectors(runFunction,argument); this._doInAllFrozenSectors(runFunction,argument); } } }; /** * This clears the nodeIndices list. We cannot use this.nodeIndices = [] because we would break the link with the * active sector. Thus we clear the nodeIndices in the active sector, then reconnect the this.nodeIndices to it. * * @private */ exports._clearNodeIndexList = function() { var sector = this._sector(); this.sectors["active"][sector]["nodeIndices"] = []; this.nodeIndices = this.sectors["active"][sector]["nodeIndices"]; }; /** * Draw the encompassing sector node * * @param ctx * @param sectorType * @private */ exports._drawSectorNodes = function(ctx,sectorType) { var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node; for (var sector in this.sectors[sectorType]) { if (this.sectors[sectorType].hasOwnProperty(sector)) { if (this.sectors[sectorType][sector]["drawingNode"] !== undefined) { this._switchToSector(sector,sectorType); minY = 1e9; maxY = -1e9; minX = 1e9; maxX = -1e9; for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; node.resize(ctx); if (minX > node.x - 0.5 * node.width) {minX = node.x - 0.5 * node.width;} if (maxX < node.x + 0.5 * node.width) {maxX = node.x + 0.5 * node.width;} if (minY > node.y - 0.5 * node.height) {minY = node.y - 0.5 * node.height;} if (maxY < node.y + 0.5 * node.height) {maxY = node.y + 0.5 * node.height;} } } node = this.sectors[sectorType][sector]["drawingNode"]; node.x = 0.5 * (maxX + minX); node.y = 0.5 * (maxY + minY); node.width = 2 * (node.x - minX); node.height = 2 * (node.y - minY); node.radius = Math.sqrt(Math.pow(0.5*node.width,2) + Math.pow(0.5*node.height,2)); node.setScale(this.scale); node._drawCircle(ctx); } } } }; exports._drawAllSectorNodes = function(ctx) { this._drawSectorNodes(ctx,"frozen"); this._drawSectorNodes(ctx,"active"); this._loadLatestSector(); }; /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { var Node = __webpack_require__(36); /** * This function can be called from the _doInAllSectors function * * @param object * @param overlappingNodes * @private */ exports._getNodesOverlappingWith = function(object, overlappingNodes) { var nodes = this.nodes; for (var nodeId in nodes) { if (nodes.hasOwnProperty(nodeId)) { if (nodes[nodeId].isOverlappingWith(object)) { overlappingNodes.push(nodeId); } } } }; /** * retrieve all nodes overlapping with given object * @param {Object} object An object with parameters left, top, right, bottom * @return {Number[]} An array with id's of the overlapping nodes * @private */ exports._getAllNodesOverlappingWith = function (object) { var overlappingNodes = []; this._doInAllActiveSectors("_getNodesOverlappingWith",object,overlappingNodes); return overlappingNodes; }; /** * Return a position object in canvasspace from a single point in screenspace * * @param pointer * @returns {{left: number, top: number, right: number, bottom: number}} * @private */ exports._pointerToPositionObject = function(pointer) { var x = this._XconvertDOMtoCanvas(pointer.x); var y = this._YconvertDOMtoCanvas(pointer.y); return { left: x, top: y, right: x, bottom: y }; }; /** * Get the top node at the a specific point (like a click) * * @param {{x: Number, y: Number}} pointer * @return {Node | null} node * @private */ exports._getNodeAt = function (pointer) { // we first check if this is an navigation controls element var positionObject = this._pointerToPositionObject(pointer); var overlappingNodes = this._getAllNodesOverlappingWith(positionObject); // if there are overlapping nodes, select the last one, this is the // one which is drawn on top of the others if (overlappingNodes.length > 0) { return this.nodes[overlappingNodes[overlappingNodes.length - 1]]; } else { return null; } }; /** * retrieve all edges overlapping with given object, selector is around center * @param {Object} object An object with parameters left, top, right, bottom * @return {Number[]} An array with id's of the overlapping nodes * @private */ exports._getEdgesOverlappingWith = function (object, overlappingEdges) { var edges = this.edges; for (var edgeId in edges) { if (edges.hasOwnProperty(edgeId)) { if (edges[edgeId].isOverlappingWith(object)) { overlappingEdges.push(edgeId); } } } }; /** * retrieve all nodes overlapping with given object * @param {Object} object An object with parameters left, top, right, bottom * @return {Number[]} An array with id's of the overlapping nodes * @private */ exports._getAllEdgesOverlappingWith = function (object) { var overlappingEdges = []; this._doInAllActiveSectors("_getEdgesOverlappingWith",object,overlappingEdges); return overlappingEdges; }; /** * Place holder. To implement change the _getNodeAt to a _getObjectAt. Have the _getObjectAt call * _getNodeAt and _getEdgesAt, then priortize the selection to user preferences. * * @param pointer * @returns {null} * @private */ exports._getEdgeAt = function(pointer) { var positionObject = this._pointerToPositionObject(pointer); var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject); if (overlappingEdges.length > 0) { return this.edges[overlappingEdges[overlappingEdges.length - 1]]; } else { return null; } }; /** * Add object to the selection array. * * @param obj * @private */ exports._addToSelection = function(obj) { if (obj instanceof Node) { this.selectionObj.nodes[obj.id] = obj; } else { this.selectionObj.edges[obj.id] = obj; } }; /** * Add object to the selection array. * * @param obj * @private */ exports._addToHover = function(obj) { if (obj instanceof Node) { this.hoverObj.nodes[obj.id] = obj; } else { this.hoverObj.edges[obj.id] = obj; } }; /** * Remove a single option from selection. * * @param {Object} obj * @private */ exports._removeFromSelection = function(obj) { if (obj instanceof Node) { delete this.selectionObj.nodes[obj.id]; } else { delete this.selectionObj.edges[obj.id]; } }; /** * Unselect all. The selectionObj is useful for this. * * @param {Boolean} [doNotTrigger] | ignore trigger * @private */ exports._unselectAll = function(doNotTrigger) { if (doNotTrigger === undefined) { doNotTrigger = false; } for(var nodeId in this.selectionObj.nodes) { if(this.selectionObj.nodes.hasOwnProperty(nodeId)) { this.selectionObj.nodes[nodeId].unselect(); } } for(var edgeId in this.selectionObj.edges) { if(this.selectionObj.edges.hasOwnProperty(edgeId)) { this.selectionObj.edges[edgeId].unselect(); } } this.selectionObj = {nodes:{},edges:{}}; if (doNotTrigger == false) { this.emit('select', this.getSelection()); } }; /** * Unselect all clusters. The selectionObj is useful for this. * * @param {Boolean} [doNotTrigger] | ignore trigger * @private */ exports._unselectClusters = function(doNotTrigger) { if (doNotTrigger === undefined) { doNotTrigger = false; } for (var nodeId in this.selectionObj.nodes) { if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { if (this.selectionObj.nodes[nodeId].clusterSize > 1) { this.selectionObj.nodes[nodeId].unselect(); this._removeFromSelection(this.selectionObj.nodes[nodeId]); } } } if (doNotTrigger == false) { this.emit('select', this.getSelection()); } }; /** * return the number of selected nodes * * @returns {number} * @private */ exports._getSelectedNodeCount = function() { var count = 0; for (var nodeId in this.selectionObj.nodes) { if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { count += 1; } } return count; }; /** * return the selected node * * @returns {number} * @private */ exports._getSelectedNode = function() { for (var nodeId in this.selectionObj.nodes) { if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { return this.selectionObj.nodes[nodeId]; } } return null; }; /** * return the selected edge * * @returns {number} * @private */ exports._getSelectedEdge = function() { for (var edgeId in this.selectionObj.edges) { if (this.selectionObj.edges.hasOwnProperty(edgeId)) { return this.selectionObj.edges[edgeId]; } } return null; }; /** * return the number of selected edges * * @returns {number} * @private */ exports._getSelectedEdgeCount = function() { var count = 0; for (var edgeId in this.selectionObj.edges) { if (this.selectionObj.edges.hasOwnProperty(edgeId)) { count += 1; } } return count; }; /** * return the number of selected objects. * * @returns {number} * @private */ exports._getSelectedObjectCount = function() { var count = 0; for(var nodeId in this.selectionObj.nodes) { if(this.selectionObj.nodes.hasOwnProperty(nodeId)) { count += 1; } } for(var edgeId in this.selectionObj.edges) { if(this.selectionObj.edges.hasOwnProperty(edgeId)) { count += 1; } } return count; }; /** * Check if anything is selected * * @returns {boolean} * @private */ exports._selectionIsEmpty = function() { for(var nodeId in this.selectionObj.nodes) { if(this.selectionObj.nodes.hasOwnProperty(nodeId)) { return false; } } for(var edgeId in this.selectionObj.edges) { if(this.selectionObj.edges.hasOwnProperty(edgeId)) { return false; } } return true; }; /** * check if one of the selected nodes is a cluster. * * @returns {boolean} * @private */ exports._clusterInSelection = function() { for(var nodeId in this.selectionObj.nodes) { if(this.selectionObj.nodes.hasOwnProperty(nodeId)) { if (this.selectionObj.nodes[nodeId].clusterSize > 1) { return true; } } } return false; }; /** * select the edges connected to the node that is being selected * * @param {Node} node * @private */ exports._selectConnectedEdges = function(node) { for (var i = 0; i < node.dynamicEdges.length; i++) { var edge = node.dynamicEdges[i]; edge.select(); this._addToSelection(edge); } }; /** * select the edges connected to the node that is being selected * * @param {Node} node * @private */ exports._hoverConnectedEdges = function(node) { for (var i = 0; i < node.dynamicEdges.length; i++) { var edge = node.dynamicEdges[i]; edge.hover = true; this._addToHover(edge); } }; /** * unselect the edges connected to the node that is being selected * * @param {Node} node * @private */ exports._unselectConnectedEdges = function(node) { for (var i = 0; i < node.dynamicEdges.length; i++) { var edge = node.dynamicEdges[i]; edge.unselect(); this._removeFromSelection(edge); } }; /** * This is called when someone clicks on a node. either select or deselect it. * If there is an existing selection and we don't want to append to it, clear the existing selection * * @param {Node || Edge} object * @param {Boolean} append * @param {Boolean} [doNotTrigger] | ignore trigger * @private */ exports._selectObject = function(object, append, doNotTrigger, highlightEdges) { if (doNotTrigger === undefined) { doNotTrigger = false; } if (highlightEdges === undefined) { highlightEdges = true; } if (this._selectionIsEmpty() == false && append == false && this.forceAppendSelection == false) { this._unselectAll(true); } if (object.selected == false) { object.select(); this._addToSelection(object); if (object instanceof Node && this.blockConnectingEdgeSelection == false && highlightEdges == true) { this._selectConnectedEdges(object); } } else { object.unselect(); this._removeFromSelection(object); } if (doNotTrigger == false) { this.emit('select', this.getSelection()); } }; /** * This is called when someone clicks on a node. either select or deselect it. * If there is an existing selection and we don't want to append to it, clear the existing selection * * @param {Node || Edge} object * @private */ exports._blurObject = function(object) { if (object.hover == true) { object.hover = false; this.emit("blurNode",{node:object.id}); } }; /** * This is called when someone clicks on a node. either select or deselect it. * If there is an existing selection and we don't want to append to it, clear the existing selection * * @param {Node || Edge} object * @private */ exports._hoverObject = function(object) { if (object.hover == false) { object.hover = true; this._addToHover(object); if (object instanceof Node) { this.emit("hoverNode",{node:object.id}); } } if (object instanceof Node) { this._hoverConnectedEdges(object); } }; /** * handles the selection part of the touch, only for navigation controls elements; * Touch is triggered before tap, also before hold. Hold triggers after a while. * This is the most responsive solution * * @param {Object} pointer * @private */ exports._handleTouch = function(pointer) { }; /** * handles the selection part of the tap; * * @param {Object} pointer * @private */ exports._handleTap = function(pointer) { var node = this._getNodeAt(pointer); if (node != null) { this._selectObject(node,false); } else { var edge = this._getEdgeAt(pointer); if (edge != null) { this._selectObject(edge,false); } else { this._unselectAll(); } } this.emit("click", this.getSelection()); this._redraw(); }; /** * handles the selection part of the double tap and opens a cluster if needed * * @param {Object} pointer * @private */ exports._handleDoubleTap = function(pointer) { var node = this._getNodeAt(pointer); if (node != null && node !== undefined) { // we reset the areaCenter here so the opening of the node will occur this.areaCenter = {"x" : this._XconvertDOMtoCanvas(pointer.x), "y" : this._YconvertDOMtoCanvas(pointer.y)}; this.openCluster(node); } this.emit("doubleClick", this.getSelection()); }; /** * Handle the onHold selection part * * @param pointer * @private */ exports._handleOnHold = function(pointer) { var node = this._getNodeAt(pointer); if (node != null) { this._selectObject(node,true); } else { var edge = this._getEdgeAt(pointer); if (edge != null) { this._selectObject(edge,true); } } this._redraw(); }; /** * handle the onRelease event. These functions are here for the navigation controls module. * * @private */ exports._handleOnRelease = function(pointer) { }; /** * * retrieve the currently selected objects * @return {{nodes: Array.<String>, edges: Array.<String>}} selection */ exports.getSelection = function() { var nodeIds = this.getSelectedNodes(); var edgeIds = this.getSelectedEdges(); return {nodes:nodeIds, edges:edgeIds}; }; /** * * retrieve the currently selected nodes * @return {String[]} selection An array with the ids of the * selected nodes. */ exports.getSelectedNodes = function() { var idArray = []; for(var nodeId in this.selectionObj.nodes) { if(this.selectionObj.nodes.hasOwnProperty(nodeId)) { idArray.push(nodeId); } } return idArray }; /** * * retrieve the currently selected edges * @return {Array} selection An array with the ids of the * selected nodes. */ exports.getSelectedEdges = function() { var idArray = []; for(var edgeId in this.selectionObj.edges) { if(this.selectionObj.edges.hasOwnProperty(edgeId)) { idArray.push(edgeId); } } return idArray; }; /** * select zero or more nodes * @param {Number[] | String[]} selection An array with the ids of the * selected nodes. */ exports.setSelection = function(selection) { var i, iMax, id; if (!selection || (selection.length == undefined)) throw 'Selection must be an array with ids'; // first unselect any selected node this._unselectAll(true); for (i = 0, iMax = selection.length; i < iMax; i++) { id = selection[i]; var node = this.nodes[id]; if (!node) { throw new RangeError('Node with id "' + id + '" not found'); } this._selectObject(node,true,true); } console.log("setSelection is deprecated. Please use selectNodes instead.") this.redraw(); }; /** * select zero or more nodes with the option to highlight edges * @param {Number[] | String[]} selection An array with the ids of the * selected nodes. * @param {boolean} [highlightEdges] */ exports.selectNodes = function(selection, highlightEdges) { var i, iMax, id; if (!selection || (selection.length == undefined)) throw 'Selection must be an array with ids'; // first unselect any selected node this._unselectAll(true); for (i = 0, iMax = selection.length; i < iMax; i++) { id = selection[i]; var node = this.nodes[id]; if (!node) { throw new RangeError('Node with id "' + id + '" not found'); } this._selectObject(node,true,true,highlightEdges); } this.redraw(); }; /** * select zero or more edges * @param {Number[] | String[]} selection An array with the ids of the * selected nodes. */ exports.selectEdges = function(selection) { var i, iMax, id; if (!selection || (selection.length == undefined)) throw 'Selection must be an array with ids'; // first unselect any selected node this._unselectAll(true); for (i = 0, iMax = selection.length; i < iMax; i++) { id = selection[i]; var edge = this.edges[id]; if (!edge) { throw new RangeError('Edge with id "' + id + '" not found'); } this._selectObject(edge,true,true,highlightEdges); } this.redraw(); }; /** * Validate the selection: remove ids of nodes which no longer exist * @private */ exports._updateSelection = function () { for(var nodeId in this.selectionObj.nodes) { if(this.selectionObj.nodes.hasOwnProperty(nodeId)) { if (!this.nodes.hasOwnProperty(nodeId)) { delete this.selectionObj.nodes[nodeId]; } } } for(var edgeId in this.selectionObj.edges) { if(this.selectionObj.edges.hasOwnProperty(edgeId)) { if (!this.edges.hasOwnProperty(edgeId)) { delete this.selectionObj.edges[edgeId]; } } } }; /***/ }, /* 53 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var Node = __webpack_require__(36); var Edge = __webpack_require__(33); /** * clears the toolbar div element of children * * @private */ exports._clearManipulatorBar = function() { while (this.manipulationDiv.hasChildNodes()) { this.manipulationDiv.removeChild(this.manipulationDiv.firstChild); } }; /** * Manipulation UI temporarily overloads certain functions to extend or replace them. To be able to restore * these functions to their original functionality, we saved them in this.cachedFunctions. * This function restores these functions to their original function. * * @private */ exports._restoreOverloadedFunctions = function() { for (var functionName in this.cachedFunctions) { if (this.cachedFunctions.hasOwnProperty(functionName)) { this[functionName] = this.cachedFunctions[functionName]; } } }; /** * Enable or disable edit-mode. * * @private */ exports._toggleEditMode = function() { this.editMode = !this.editMode; var toolbar = document.getElementById("network-manipulationDiv"); var closeDiv = document.getElementById("network-manipulation-closeDiv"); var editModeDiv = document.getElementById("network-manipulation-editMode"); if (this.editMode == true) { toolbar.style.display="block"; closeDiv.style.display="block"; editModeDiv.style.display="none"; closeDiv.onclick = this._toggleEditMode.bind(this); } else { toolbar.style.display="none"; closeDiv.style.display="none"; editModeDiv.style.display="block"; closeDiv.onclick = null; } this._createManipulatorBar() }; /** * main function, creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar. * * @private */ exports._createManipulatorBar = function() { // remove bound functions if (this.boundFunction) { this.off('select', this.boundFunction); } if (this.edgeBeingEdited !== undefined) { this.edgeBeingEdited._disableControlNodes(); this.edgeBeingEdited = undefined; this.selectedControlNode = null; this.controlNodesActive = false; } // restore overloaded functions this._restoreOverloadedFunctions(); // resume calculation this.freezeSimulation = false; // reset global variables this.blockConnectingEdgeSelection = false; this.forceAppendSelection = false; if (this.editMode == true) { while (this.manipulationDiv.hasChildNodes()) { this.manipulationDiv.removeChild(this.manipulationDiv.firstChild); } // add the icons to the manipulator div this.manipulationDiv.innerHTML = "" + "<span class='network-manipulationUI add' id='network-manipulate-addNode'>" + "<span class='network-manipulationLabel'>"+this.constants.labels['add'] +"</span></span>" + "<div class='network-seperatorLine'></div>" + "<span class='network-manipulationUI connect' id='network-manipulate-connectNode'>" + "<span class='network-manipulationLabel'>"+this.constants.labels['link'] +"</span></span>"; if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) { this.manipulationDiv.innerHTML += "" + "<div class='network-seperatorLine'></div>" + "<span class='network-manipulationUI edit' id='network-manipulate-editNode'>" + "<span class='network-manipulationLabel'>"+this.constants.labels['editNode'] +"</span></span>"; } else if (this._getSelectedEdgeCount() == 1 && this._getSelectedNodeCount() == 0) { this.manipulationDiv.innerHTML += "" + "<div class='network-seperatorLine'></div>" + "<span class='network-manipulationUI edit' id='network-manipulate-editEdge'>" + "<span class='network-manipulationLabel'>"+this.constants.labels['editEdge'] +"</span></span>"; } if (this._selectionIsEmpty() == false) { this.manipulationDiv.innerHTML += "" + "<div class='network-seperatorLine'></div>" + "<span class='network-manipulationUI delete' id='network-manipulate-delete'>" + "<span class='network-manipulationLabel'>"+this.constants.labels['del'] +"</span></span>"; } // bind the icons var addNodeButton = document.getElementById("network-manipulate-addNode"); addNodeButton.onclick = this._createAddNodeToolbar.bind(this); var addEdgeButton = document.getElementById("network-manipulate-connectNode"); addEdgeButton.onclick = this._createAddEdgeToolbar.bind(this); if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) { var editButton = document.getElementById("network-manipulate-editNode"); editButton.onclick = this._editNode.bind(this); } else if (this._getSelectedEdgeCount() == 1 && this._getSelectedNodeCount() == 0) { var editButton = document.getElementById("network-manipulate-editEdge"); editButton.onclick = this._createEditEdgeToolbar.bind(this); } if (this._selectionIsEmpty() == false) { var deleteButton = document.getElementById("network-manipulate-delete"); deleteButton.onclick = this._deleteSelected.bind(this); } var closeDiv = document.getElementById("network-manipulation-closeDiv"); closeDiv.onclick = this._toggleEditMode.bind(this); this.boundFunction = this._createManipulatorBar.bind(this); this.on('select', this.boundFunction); } else { this.editModeDiv.innerHTML = "" + "<span class='network-manipulationUI edit editmode' id='network-manipulate-editModeButton'>" + "<span class='network-manipulationLabel'>" + this.constants.labels['edit'] + "</span></span>"; var editModeButton = document.getElementById("network-manipulate-editModeButton"); editModeButton.onclick = this._toggleEditMode.bind(this); } }; /** * Create the toolbar for adding Nodes * * @private */ exports._createAddNodeToolbar = function() { // clear the toolbar this._clearManipulatorBar(); if (this.boundFunction) { this.off('select', this.boundFunction); } // create the toolbar contents this.manipulationDiv.innerHTML = "" + "<span class='network-manipulationUI back' id='network-manipulate-back'>" + "<span class='network-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" + "<div class='network-seperatorLine'></div>" + "<span class='network-manipulationUI none' id='network-manipulate-back'>" + "<span id='network-manipulatorLabel' class='network-manipulationLabel'>" + this.constants.labels['addDescription'] + "</span></span>"; // bind the icon var backButton = document.getElementById("network-manipulate-back"); backButton.onclick = this._createManipulatorBar.bind(this); // we use the boundFunction so we can reference it when we unbind it from the "select" event. this.boundFunction = this._addNode.bind(this); this.on('select', this.boundFunction); }; /** * create the toolbar to connect nodes * * @private */ exports._createAddEdgeToolbar = function() { // clear the toolbar this._clearManipulatorBar(); this._unselectAll(true); this.freezeSimulation = true; if (this.boundFunction) { this.off('select', this.boundFunction); } this._unselectAll(); this.forceAppendSelection = false; this.blockConnectingEdgeSelection = true; this.manipulationDiv.innerHTML = "" + "<span class='network-manipulationUI back' id='network-manipulate-back'>" + "<span class='network-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" + "<div class='network-seperatorLine'></div>" + "<span class='network-manipulationUI none' id='network-manipulate-back'>" + "<span id='network-manipulatorLabel' class='network-manipulationLabel'>" + this.constants.labels['linkDescription'] + "</span></span>"; // bind the icon var backButton = document.getElementById("network-manipulate-back"); backButton.onclick = this._createManipulatorBar.bind(this); // we use the boundFunction so we can reference it when we unbind it from the "select" event. this.boundFunction = this._handleConnect.bind(this); this.on('select', this.boundFunction); // temporarily overload functions this.cachedFunctions["_handleTouch"] = this._handleTouch; this.cachedFunctions["_handleOnRelease"] = this._handleOnRelease; this._handleTouch = this._handleConnect; this._handleOnRelease = this._finishConnect; // redraw to show the unselect this._redraw(); }; /** * create the toolbar to edit edges * * @private */ exports._createEditEdgeToolbar = function() { // clear the toolbar this._clearManipulatorBar(); this.controlNodesActive = true; if (this.boundFunction) { this.off('select', this.boundFunction); } this.edgeBeingEdited = this._getSelectedEdge(); this.edgeBeingEdited._enableControlNodes(); this.manipulationDiv.innerHTML = "" + "<span class='network-manipulationUI back' id='network-manipulate-back'>" + "<span class='network-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" + "<div class='network-seperatorLine'></div>" + "<span class='network-manipulationUI none' id='network-manipulate-back'>" + "<span id='network-manipulatorLabel' class='network-manipulationLabel'>" + this.constants.labels['editEdgeDescription'] + "</span></span>"; // bind the icon var backButton = document.getElementById("network-manipulate-back"); backButton.onclick = this._createManipulatorBar.bind(this); // temporarily overload functions this.cachedFunctions["_handleTouch"] = this._handleTouch; this.cachedFunctions["_handleOnRelease"] = this._handleOnRelease; this.cachedFunctions["_handleTap"] = this._handleTap; this.cachedFunctions["_handleDragStart"] = this._handleDragStart; this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag; this._handleTouch = this._selectControlNode; this._handleTap = function () {}; this._handleOnDrag = this._controlNodeDrag; this._handleDragStart = function () {} this._handleOnRelease = this._releaseControlNode; // redraw to show the unselect this._redraw(); }; /** * the function bound to the selection event. It checks if you want to connect a cluster and changes the description * to walk the user through the process. * * @private */ exports._selectControlNode = function(pointer) { this.edgeBeingEdited.controlNodes.from.unselect(); this.edgeBeingEdited.controlNodes.to.unselect(); this.selectedControlNode = this.edgeBeingEdited._getSelectedControlNode(this._XconvertDOMtoCanvas(pointer.x),this._YconvertDOMtoCanvas(pointer.y)); if (this.selectedControlNode !== null) { this.selectedControlNode.select(); this.freezeSimulation = true; } this._redraw(); }; /** * the function bound to the selection event. It checks if you want to connect a cluster and changes the description * to walk the user through the process. * * @private */ exports._controlNodeDrag = function(event) { var pointer = this._getPointer(event.gesture.center); if (this.selectedControlNode !== null && this.selectedControlNode !== undefined) { this.selectedControlNode.x = this._XconvertDOMtoCanvas(pointer.x); this.selectedControlNode.y = this._YconvertDOMtoCanvas(pointer.y); } this._redraw(); }; exports._releaseControlNode = function(pointer) { var newNode = this._getNodeAt(pointer); if (newNode != null) { if (this.edgeBeingEdited.controlNodes.from.selected == true) { this._editEdge(newNode.id, this.edgeBeingEdited.to.id); this.edgeBeingEdited.controlNodes.from.unselect(); } if (this.edgeBeingEdited.controlNodes.to.selected == true) { this._editEdge(this.edgeBeingEdited.from.id, newNode.id); this.edgeBeingEdited.controlNodes.to.unselect(); } } else { this.edgeBeingEdited._restoreControlNodes(); } this.freezeSimulation = false; this._redraw(); }; /** * the function bound to the selection event. It checks if you want to connect a cluster and changes the description * to walk the user through the process. * * @private */ exports._handleConnect = function(pointer) { if (this._getSelectedNodeCount() == 0) { var node = this._getNodeAt(pointer); if (node != null) { if (node.clusterSize > 1) { alert("Cannot create edges to a cluster.") } else { this._selectObject(node,false); // create a node the temporary line can look at this.sectors['support']['nodes']['targetNode'] = new Node({id:'targetNode'},{},{},this.constants); this.sectors['support']['nodes']['targetNode'].x = node.x; this.sectors['support']['nodes']['targetNode'].y = node.y; this.sectors['support']['nodes']['targetViaNode'] = new Node({id:'targetViaNode'},{},{},this.constants); this.sectors['support']['nodes']['targetViaNode'].x = node.x; this.sectors['support']['nodes']['targetViaNode'].y = node.y; this.sectors['support']['nodes']['targetViaNode'].parentEdgeId = "connectionEdge"; // create a temporary edge this.edges['connectionEdge'] = new Edge({id:"connectionEdge",from:node.id,to:this.sectors['support']['nodes']['targetNode'].id}, this, this.constants); this.edges['connectionEdge'].from = node; this.edges['connectionEdge'].connected = true; this.edges['connectionEdge'].smooth = true; this.edges['connectionEdge'].selected = true; this.edges['connectionEdge'].to = this.sectors['support']['nodes']['targetNode']; this.edges['connectionEdge'].via = this.sectors['support']['nodes']['targetViaNode']; this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag; this._handleOnDrag = function(event) { var pointer = this._getPointer(event.gesture.center); this.sectors['support']['nodes']['targetNode'].x = this._XconvertDOMtoCanvas(pointer.x); this.sectors['support']['nodes']['targetNode'].y = this._YconvertDOMtoCanvas(pointer.y); this.sectors['support']['nodes']['targetViaNode'].x = 0.5 * (this._XconvertDOMtoCanvas(pointer.x) + this.edges['connectionEdge'].from.x); this.sectors['support']['nodes']['targetViaNode'].y = this._YconvertDOMtoCanvas(pointer.y); }; this.moving = true; this.start(); } } } }; exports._finishConnect = function(pointer) { if (this._getSelectedNodeCount() == 1) { // restore the drag function this._handleOnDrag = this.cachedFunctions["_handleOnDrag"]; delete this.cachedFunctions["_handleOnDrag"]; // remember the edge id var connectFromId = this.edges['connectionEdge'].fromId; // remove the temporary nodes and edge delete this.edges['connectionEdge']; delete this.sectors['support']['nodes']['targetNode']; delete this.sectors['support']['nodes']['targetViaNode']; var node = this._getNodeAt(pointer); if (node != null) { if (node.clusterSize > 1) { alert("Cannot create edges to a cluster.") } else { this._createEdge(connectFromId,node.id); this._createManipulatorBar(); } } this._unselectAll(); } }; /** * Adds a node on the specified location */ exports._addNode = function() { if (this._selectionIsEmpty() && this.editMode == true) { var positionObject = this._pointerToPositionObject(this.pointerPosition); var defaultData = {id:util.randomUUID(),x:positionObject.left,y:positionObject.top,label:"new",allowedToMoveX:true,allowedToMoveY:true}; if (this.triggerFunctions.add) { if (this.triggerFunctions.add.length == 2) { var me = this; this.triggerFunctions.add(defaultData, function(finalizedData) { me.nodesData.add(finalizedData); me._createManipulatorBar(); me.moving = true; me.start(); }); } else { alert(this.constants.labels['addError']); this._createManipulatorBar(); this.moving = true; this.start(); } } else { this.nodesData.add(defaultData); this._createManipulatorBar(); this.moving = true; this.start(); } } }; /** * connect two nodes with a new edge. * * @private */ exports._createEdge = function(sourceNodeId,targetNodeId) { if (this.editMode == true) { var defaultData = {from:sourceNodeId, to:targetNodeId}; if (this.triggerFunctions.connect) { if (this.triggerFunctions.connect.length == 2) { var me = this; this.triggerFunctions.connect(defaultData, function(finalizedData) { me.edgesData.add(finalizedData); me.moving = true; me.start(); }); } else { alert(this.constants.labels["linkError"]); this.moving = true; this.start(); } } else { this.edgesData.add(defaultData); this.moving = true; this.start(); } } }; /** * connect two nodes with a new edge. * * @private */ exports._editEdge = function(sourceNodeId,targetNodeId) { if (this.editMode == true) { var defaultData = {id: this.edgeBeingEdited.id, from:sourceNodeId, to:targetNodeId}; if (this.triggerFunctions.editEdge) { if (this.triggerFunctions.editEdge.length == 2) { var me = this; this.triggerFunctions.editEdge(defaultData, function(finalizedData) { me.edgesData.update(finalizedData); me.moving = true; me.start(); }); } else { alert(this.constants.labels["linkError"]); this.moving = true; this.start(); } } else { this.edgesData.update(defaultData); this.moving = true; this.start(); } } }; /** * Create the toolbar to edit the selected node. The label and the color can be changed. Other colors are derived from the chosen color. * * @private */ exports._editNode = function() { if (this.triggerFunctions.edit && this.editMode == true) { var node = this._getSelectedNode(); var data = {id:node.id, label: node.label, group: node.options.group, shape: node.options.shape, color: { background:node.options.color.background, border:node.options.color.border, highlight: { background:node.options.color.highlight.background, border:node.options.color.highlight.border } }}; if (this.triggerFunctions.edit.length == 2) { var me = this; this.triggerFunctions.edit(data, function (finalizedData) { me.nodesData.update(finalizedData); me._createManipulatorBar(); me.moving = true; me.start(); }); } else { alert(this.constants.labels["editError"]); } } else { alert(this.constants.labels["editBoundError"]); } }; /** * delete everything in the selection * * @private */ exports._deleteSelected = function() { if (!this._selectionIsEmpty() && this.editMode == true) { if (!this._clusterInSelection()) { var selectedNodes = this.getSelectedNodes(); var selectedEdges = this.getSelectedEdges(); if (this.triggerFunctions.del) { var me = this; var data = {nodes: selectedNodes, edges: selectedEdges}; if (this.triggerFunctions.del.length = 2) { this.triggerFunctions.del(data, function (finalizedData) { me.edgesData.remove(finalizedData.edges); me.nodesData.remove(finalizedData.nodes); me._unselectAll(); me.moving = true; me.start(); }); } else { alert(this.constants.labels["deleteError"]) } } else { this.edgesData.remove(selectedEdges); this.nodesData.remove(selectedNodes); this._unselectAll(); this.moving = true; this.start(); } } else { alert(this.constants.labels["deleteClusterError"]); } } }; /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var Hammer = __webpack_require__(41); exports._cleanNavigation = function() { // clean up previous navigation items var wrapper = document.getElementById('network-navigation_wrapper'); if (wrapper != null) { this.containerElement.removeChild(wrapper); } document.onmouseup = null; }; /** * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false. * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas. * * @private */ exports._loadNavigationElements = function() { this._cleanNavigation(); this.navigationDivs = {}; var navigationDivs = ['up','down','left','right','zoomIn','zoomOut','zoomExtends']; var navigationDivActions = ['_moveUp','_moveDown','_moveLeft','_moveRight','_zoomIn','_zoomOut','zoomExtent']; this.navigationDivs['wrapper'] = document.createElement('div'); this.navigationDivs['wrapper'].id = "network-navigation_wrapper"; this.navigationDivs['wrapper'].style.position = "absolute"; this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px"; this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px"; this.containerElement.insertBefore(this.navigationDivs['wrapper'],this.frame); var me = this; for (var i = 0; i < navigationDivs.length; i++) { this.navigationDivs[navigationDivs[i]] = document.createElement('div'); this.navigationDivs[navigationDivs[i]].id = "network-navigation_" + navigationDivs[i]; this.navigationDivs[navigationDivs[i]].className = "network-navigation " + navigationDivs[i]; this.navigationDivs['wrapper'].appendChild(this.navigationDivs[navigationDivs[i]]); var hammer = Hammer(this.navigationDivs[navigationDivs[i]], {prevent_default: true}); hammer.on("touch", me[navigationDivActions[i]].bind(me)); } var hammer = Hammer(document, {prevent_default: false}); hammer.on("release", me._stopMovement.bind(me)); }; /** * this stops all movement induced by the navigation buttons * * @private */ exports._stopMovement = function() { this._xStopMoving(); this._yStopMoving(); this._stopZoom(); }; /** * move the screen up * By using the increments, instead of adding a fixed number to the translation, we keep fluent and * instant movement. The onKeypress event triggers immediately, then pauses, then triggers frequently * To avoid this behaviour, we do the translation in the start loop. * * @private */ exports._moveUp = function(event) { this.yIncrement = this.constants.keyboard.speed.y; this.start(); // if there is no node movement, the calculation wont be done }; /** * move the screen down * @private */ exports._moveDown = function(event) { this.yIncrement = -this.constants.keyboard.speed.y; this.start(); // if there is no node movement, the calculation wont be done }; /** * move the screen left * @private */ exports._moveLeft = function(event) { this.xIncrement = this.constants.keyboard.speed.x; this.start(); // if there is no node movement, the calculation wont be done }; /** * move the screen right * @private */ exports._moveRight = function(event) { this.xIncrement = -this.constants.keyboard.speed.y; this.start(); // if there is no node movement, the calculation wont be done }; /** * Zoom in, using the same method as the movement. * @private */ exports._zoomIn = function(event) { this.zoomIncrement = this.constants.keyboard.speed.zoom; this.start(); // if there is no node movement, the calculation wont be done }; /** * Zoom out * @private */ exports._zoomOut = function() { this.zoomIncrement = -this.constants.keyboard.speed.zoom; this.start(); // if there is no node movement, the calculation wont be done util.preventDefault(event); }; /** * Stop zooming and unhighlight the zoom controls * @private */ exports._stopZoom = function() { this.zoomIncrement = 0; }; /** * Stop moving in the Y direction and unHighlight the up and down * @private */ exports._yStopMoving = function() { this.yIncrement = 0; }; /** * Stop moving in the X direction and unHighlight left and right. * @private */ exports._xStopMoving = function() { this.xIncrement = 0; }; /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { exports._resetLevels = function() { for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { var node = this.nodes[nodeId]; if (node.preassignedLevel == false) { node.level = -1; } } } }; /** * This is the main function to layout the nodes in a hierarchical way. * It checks if the node details are supplied correctly * * @private */ exports._setupHierarchicalLayout = function() { if (this.constants.hierarchicalLayout.enabled == true && this.nodeIndices.length > 0) { if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "DU") { this.constants.hierarchicalLayout.levelSeparation *= -1; } else { this.constants.hierarchicalLayout.levelSeparation = Math.abs(this.constants.hierarchicalLayout.levelSeparation); } if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "LR") { if (this.constants.smoothCurves.enabled == true) { this.constants.smoothCurves.type = "vertical"; } } else { if (this.constants.smoothCurves.enabled == true) { this.constants.smoothCurves.type = "horizontal"; } } // get the size of the largest hubs and check if the user has defined a level for a node. var hubsize = 0; var node, nodeId; var definedLevel = false; var undefinedLevel = false; for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; if (node.level != -1) { definedLevel = true; } else { undefinedLevel = true; } if (hubsize < node.edges.length) { hubsize = node.edges.length; } } } // if the user defined some levels but not all, alert and run without hierarchical layout if (undefinedLevel == true && definedLevel == true) { alert("To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes."); this.zoomExtent(true,this.constants.clustering.enabled); if (!this.constants.clustering.enabled) { this.start(); } } else { // setup the system to use hierarchical method. this._changeConstants(); // define levels if undefined by the users. Based on hubsize if (undefinedLevel == true) { this._determineLevels(hubsize); } // check the distribution of the nodes per level. var distribution = this._getDistribution(); // place the nodes on the canvas. This also stablilizes the system. this._placeNodesByHierarchy(distribution); // start the simulation. this.start(); } } }; /** * This function places the nodes on the canvas based on the hierarchial distribution. * * @param {Object} distribution | obtained by the function this._getDistribution() * @private */ exports._placeNodesByHierarchy = function(distribution) { var nodeId, node; // start placing all the level 0 nodes first. Then recursively position their branches. for (var level in distribution) { if (distribution.hasOwnProperty(level)) { for (nodeId in distribution[level].nodes) { if (distribution[level].nodes.hasOwnProperty(nodeId)) { node = distribution[level].nodes[nodeId]; if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") { if (node.xFixed) { node.x = distribution[level].minPos; node.xFixed = false; distribution[level].minPos += distribution[level].nodeSpacing; } } else { if (node.yFixed) { node.y = distribution[level].minPos; node.yFixed = false; distribution[level].minPos += distribution[level].nodeSpacing; } } this._placeBranchNodes(node.edges,node.id,distribution,node.level); } } } } // stabilize the system after positioning. This function calls zoomExtent. this._stabilize(); }; /** * This function get the distribution of levels based on hubsize * * @returns {Object} * @private */ exports._getDistribution = function() { var distribution = {}; var nodeId, node, level; // we fix Y because the hierarchy is vertical, we fix X so we do not give a node an x position for a second time. // the fix of X is removed after the x value has been set. for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; node.xFixed = true; node.yFixed = true; if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") { node.y = this.constants.hierarchicalLayout.levelSeparation*node.level; } else { node.x = this.constants.hierarchicalLayout.levelSeparation*node.level; } if (distribution[node.level] === undefined) { distribution[node.level] = {amount: 0, nodes: {}, minPos:0, nodeSpacing:0}; } distribution[node.level].amount += 1; distribution[node.level].nodes[nodeId] = node; } } // determine the largest amount of nodes of all levels var maxCount = 0; for (level in distribution) { if (distribution.hasOwnProperty(level)) { if (maxCount < distribution[level].amount) { maxCount = distribution[level].amount; } } } // set the initial position and spacing of each nodes accordingly for (level in distribution) { if (distribution.hasOwnProperty(level)) { distribution[level].nodeSpacing = (maxCount + 1) * this.constants.hierarchicalLayout.nodeSpacing; distribution[level].nodeSpacing /= (distribution[level].amount + 1); distribution[level].minPos = distribution[level].nodeSpacing - (0.5 * (distribution[level].amount + 1) * distribution[level].nodeSpacing); } } return distribution; }; /** * this function allocates nodes in levels based on the recursive branching from the largest hubs. * * @param hubsize * @private */ exports._determineLevels = function(hubsize) { var nodeId, node; // determine hubs for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; if (node.edges.length == hubsize) { node.level = 0; } } } // branch from hubs for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; if (node.level == 0) { this._setLevel(1,node.edges,node.id); } } } }; /** * Since hierarchical layout does not support: * - smooth curves (based on the physics), * - clustering (based on dynamic node counts) * * We disable both features so there will be no problems. * * @private */ exports._changeConstants = function() { this.constants.clustering.enabled = false; this.constants.physics.barnesHut.enabled = false; this.constants.physics.hierarchicalRepulsion.enabled = true; this._loadSelectedForceSolver(); if (this.constants.smoothCurves.enabled == true) { this.constants.smoothCurves.dynamic = false; } this._configureSmoothCurves(); }; /** * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes * on a X position that ensures there will be no overlap. * * @param edges * @param parentId * @param distribution * @param parentLevel * @private */ exports._placeBranchNodes = function(edges, parentId, distribution, parentLevel) { for (var i = 0; i < edges.length; i++) { var childNode = null; if (edges[i].toId == parentId) { childNode = edges[i].from; } else { childNode = edges[i].to; } // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here. var nodeMoved = false; if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") { if (childNode.xFixed && childNode.level > parentLevel) { childNode.xFixed = false; childNode.x = distribution[childNode.level].minPos; nodeMoved = true; } } else { if (childNode.yFixed && childNode.level > parentLevel) { childNode.yFixed = false; childNode.y = distribution[childNode.level].minPos; nodeMoved = true; } } if (nodeMoved == true) { distribution[childNode.level].minPos += distribution[childNode.level].nodeSpacing; if (childNode.edges.length > 1) { this._placeBranchNodes(childNode.edges,childNode.id,distribution,childNode.level); } } } }; /** * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level. * * @param level * @param edges * @param parentId * @private */ exports._setLevel = function(level, edges, parentId) { for (var i = 0; i < edges.length; i++) { var childNode = null; if (edges[i].toId == parentId) { childNode = edges[i].from; } else { childNode = edges[i].to; } if (childNode.level == -1 || childNode.level > level) { childNode.level = level; if (edges.length > 1) { this._setLevel(level+1, childNode.edges, childNode.id); } } } }; /** * Unfix nodes * * @private */ exports._restoreNodes = function() { for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { this.nodes[nodeId].xFixed = false; this.nodes[nodeId].yFixed = false; } } }; /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var RepulsionMixin = __webpack_require__(59); var HierarchialRepulsionMixin = __webpack_require__(60); var BarnesHutMixin = __webpack_require__(61); /** * Toggling barnes Hut calculation on and off. * * @private */ exports._toggleBarnesHut = function () { this.constants.physics.barnesHut.enabled = !this.constants.physics.barnesHut.enabled; this._loadSelectedForceSolver(); this.moving = true; this.start(); }; /** * This loads the node force solver based on the barnes hut or repulsion algorithm * * @private */ exports._loadSelectedForceSolver = function () { // this overloads the this._calculateNodeForces if (this.constants.physics.barnesHut.enabled == true) { this._clearMixin(RepulsionMixin); this._clearMixin(HierarchialRepulsionMixin); this.constants.physics.centralGravity = this.constants.physics.barnesHut.centralGravity; this.constants.physics.springLength = this.constants.physics.barnesHut.springLength; this.constants.physics.springConstant = this.constants.physics.barnesHut.springConstant; this.constants.physics.damping = this.constants.physics.barnesHut.damping; this._loadMixin(BarnesHutMixin); } else if (this.constants.physics.hierarchicalRepulsion.enabled == true) { this._clearMixin(BarnesHutMixin); this._clearMixin(RepulsionMixin); this.constants.physics.centralGravity = this.constants.physics.hierarchicalRepulsion.centralGravity; this.constants.physics.springLength = this.constants.physics.hierarchicalRepulsion.springLength; this.constants.physics.springConstant = this.constants.physics.hierarchicalRepulsion.springConstant; this.constants.physics.damping = this.constants.physics.hierarchicalRepulsion.damping; this._loadMixin(HierarchialRepulsionMixin); } else { this._clearMixin(BarnesHutMixin); this._clearMixin(HierarchialRepulsionMixin); this.barnesHutTree = undefined; this.constants.physics.centralGravity = this.constants.physics.repulsion.centralGravity; this.constants.physics.springLength = this.constants.physics.repulsion.springLength; this.constants.physics.springConstant = this.constants.physics.repulsion.springConstant; this.constants.physics.damping = this.constants.physics.repulsion.damping; this._loadMixin(RepulsionMixin); } }; /** * Before calculating the forces, we check if we need to cluster to keep up performance and we check * if there is more than one node. If it is just one node, we dont calculate anything. * * @private */ exports._initializeForceCalculation = function () { // stop calculation if there is only one node if (this.nodeIndices.length == 1) { this.nodes[this.nodeIndices[0]]._setForce(0, 0); } else { // if there are too many nodes on screen, we cluster without repositioning if (this.nodeIndices.length > this.constants.clustering.clusterThreshold && this.constants.clustering.enabled == true) { this.clusterToFit(this.constants.clustering.reduceToNodes, false); } // we now start the force calculation this._calculateForces(); } }; /** * Calculate the external forces acting on the nodes * Forces are caused by: edges, repulsing forces between nodes, gravity * @private */ exports._calculateForces = function () { // Gravity is required to keep separated groups from floating off // the forces are reset to zero in this loop by using _setForce instead // of _addForce this._calculateGravitationalForces(); this._calculateNodeForces(); if (this.constants.physics.springConstant > 0) { if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) { this._calculateSpringForcesWithSupport(); } else { if (this.constants.physics.hierarchicalRepulsion.enabled == true) { this._calculateHierarchicalSpringForces(); } else { this._calculateSpringForces(); } } } }; /** * Smooth curves are created by adding invisible nodes in the center of the edges. These nodes are also * handled in the calculateForces function. We then use a quadratic curve with the center node as control. * This function joins the datanodes and invisible (called support) nodes into one object. * We do this so we do not contaminate this.nodes with the support nodes. * * @private */ exports._updateCalculationNodes = function () { if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) { this.calculationNodes = {}; this.calculationNodeIndices = []; for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { this.calculationNodes[nodeId] = this.nodes[nodeId]; } } var supportNodes = this.sectors['support']['nodes']; for (var supportNodeId in supportNodes) { if (supportNodes.hasOwnProperty(supportNodeId)) { if (this.edges.hasOwnProperty(supportNodes[supportNodeId].parentEdgeId)) { this.calculationNodes[supportNodeId] = supportNodes[supportNodeId]; } else { supportNodes[supportNodeId]._setForce(0, 0); } } } for (var idx in this.calculationNodes) { if (this.calculationNodes.hasOwnProperty(idx)) { this.calculationNodeIndices.push(idx); } } } else { this.calculationNodes = this.nodes; this.calculationNodeIndices = this.nodeIndices; } }; /** * this function applies the central gravity effect to keep groups from floating off * * @private */ exports._calculateGravitationalForces = function () { var dx, dy, distance, node, i; var nodes = this.calculationNodes; var gravity = this.constants.physics.centralGravity; var gravityForce = 0; for (i = 0; i < this.calculationNodeIndices.length; i++) { node = nodes[this.calculationNodeIndices[i]]; node.damping = this.constants.physics.damping; // possibly add function to alter damping properties of clusters. // gravity does not apply when we are in a pocket sector if (this._sector() == "default" && gravity != 0) { dx = -node.x; dy = -node.y; distance = Math.sqrt(dx * dx + dy * dy); gravityForce = (distance == 0) ? 0 : (gravity / distance); node.fx = dx * gravityForce; node.fy = dy * gravityForce; } else { node.fx = 0; node.fy = 0; } } }; /** * this function calculates the effects of the springs in the case of unsmooth curves. * * @private */ exports._calculateSpringForces = function () { var edgeLength, edge, edgeId; var dx, dy, fx, fy, springForce, distance; var edges = this.edges; // forces caused by the edges, modelled as springs for (edgeId in edges) { if (edges.hasOwnProperty(edgeId)) { edge = edges[edgeId]; if (edge.connected) { // only calculate forces if nodes are in the same sector if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) { edgeLength = edge.physics.springLength; // this implies that the edges between big clusters are longer edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth; dx = (edge.from.x - edge.to.x); dy = (edge.from.y - edge.to.y); distance = Math.sqrt(dx * dx + dy * dy); if (distance == 0) { distance = 0.01; } // the 1/distance is so the fx and fy can be calculated without sine or cosine. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance; fx = dx * springForce; fy = dy * springForce; edge.from.fx += fx; edge.from.fy += fy; edge.to.fx -= fx; edge.to.fy -= fy; } } } } }; /** * This function calculates the springforces on the nodes, accounting for the support nodes. * * @private */ exports._calculateSpringForcesWithSupport = function () { var edgeLength, edge, edgeId, combinedClusterSize; var edges = this.edges; // forces caused by the edges, modelled as springs for (edgeId in edges) { if (edges.hasOwnProperty(edgeId)) { edge = edges[edgeId]; if (edge.connected) { // only calculate forces if nodes are in the same sector if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) { if (edge.via != null) { var node1 = edge.to; var node2 = edge.via; var node3 = edge.from; edgeLength = edge.physics.springLength; combinedClusterSize = node1.clusterSize + node3.clusterSize - 2; // this implies that the edges between big clusters are longer edgeLength += combinedClusterSize * this.constants.clustering.edgeGrowth; this._calculateSpringForce(node1, node2, 0.5 * edgeLength); this._calculateSpringForce(node2, node3, 0.5 * edgeLength); } } } } } }; /** * This is the code actually performing the calculation for the function above. It is split out to avoid repetition. * * @param node1 * @param node2 * @param edgeLength * @private */ exports._calculateSpringForce = function (node1, node2, edgeLength) { var dx, dy, fx, fy, springForce, distance; dx = (node1.x - node2.x); dy = (node1.y - node2.y); distance = Math.sqrt(dx * dx + dy * dy); if (distance == 0) { distance = 0.01; } // the 1/distance is so the fx and fy can be calculated without sine or cosine. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance; fx = dx * springForce; fy = dy * springForce; node1.fx += fx; node1.fy += fy; node2.fx -= fx; node2.fy -= fy; }; /** * Load the HTML for the physics config and bind it * @private */ exports._loadPhysicsConfiguration = function () { if (this.physicsConfiguration === undefined) { this.backupConstants = {}; util.deepExtend(this.backupConstants,this.constants); var hierarchicalLayoutDirections = ["LR", "RL", "UD", "DU"]; this.physicsConfiguration = document.createElement('div'); this.physicsConfiguration.className = "PhysicsConfiguration"; this.physicsConfiguration.innerHTML = '' + '<table><tr><td><b>Simulation Mode:</b></td></tr>' + '<tr>' + '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod1" value="BH" checked="checked">Barnes Hut</td>' + '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod2" value="R">Repulsion</td>' + '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod3" value="H">Hierarchical</td>' + '</tr>' + '</table>' + '<table id="graph_BH_table" style="display:none">' + '<tr><td><b>Barnes Hut</b></td></tr>' + '<tr>' + '<td width="150px">gravitationalConstant</td><td>0</td><td><input type="range" min="0" max="20000" value="' + (-1 * this.constants.physics.barnesHut.gravitationalConstant) + '" step="25" style="width:300px" id="graph_BH_gc"></td><td width="50px">-20000</td><td><input value="' + (-1 * this.constants.physics.barnesHut.gravitationalConstant) + '" id="graph_BH_gc_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">centralGravity</td><td>0</td><td><input type="range" min="0" max="3" value="' + this.constants.physics.barnesHut.centralGravity + '" step="0.05" style="width:300px" id="graph_BH_cg"></td><td>3</td><td><input value="' + this.constants.physics.barnesHut.centralGravity + '" id="graph_BH_cg_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">springLength</td><td>0</td><td><input type="range" min="0" max="500" value="' + this.constants.physics.barnesHut.springLength + '" step="1" style="width:300px" id="graph_BH_sl"></td><td>500</td><td><input value="' + this.constants.physics.barnesHut.springLength + '" id="graph_BH_sl_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">springConstant</td><td>0</td><td><input type="range" min="0" max="0.5" value="' + this.constants.physics.barnesHut.springConstant + '" step="0.001" style="width:300px" id="graph_BH_sc"></td><td>0.5</td><td><input value="' + this.constants.physics.barnesHut.springConstant + '" id="graph_BH_sc_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">damping</td><td>0</td><td><input type="range" min="0" max="0.3" value="' + this.constants.physics.barnesHut.damping + '" step="0.005" style="width:300px" id="graph_BH_damp"></td><td>0.3</td><td><input value="' + this.constants.physics.barnesHut.damping + '" id="graph_BH_damp_value" style="width:60px"></td>' + '</tr>' + '</table>' + '<table id="graph_R_table" style="display:none">' + '<tr><td><b>Repulsion</b></td></tr>' + '<tr>' + '<td width="150px">nodeDistance</td><td>0</td><td><input type="range" min="0" max="300" value="' + this.constants.physics.repulsion.nodeDistance + '" step="1" style="width:300px" id="graph_R_nd"></td><td width="50px">300</td><td><input value="' + this.constants.physics.repulsion.nodeDistance + '" id="graph_R_nd_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">centralGravity</td><td>0</td><td><input type="range" min="0" max="3" value="' + this.constants.physics.repulsion.centralGravity + '" step="0.05" style="width:300px" id="graph_R_cg"></td><td>3</td><td><input value="' + this.constants.physics.repulsion.centralGravity + '" id="graph_R_cg_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">springLength</td><td>0</td><td><input type="range" min="0" max="500" value="' + this.constants.physics.repulsion.springLength + '" step="1" style="width:300px" id="graph_R_sl"></td><td>500</td><td><input value="' + this.constants.physics.repulsion.springLength + '" id="graph_R_sl_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">springConstant</td><td>0</td><td><input type="range" min="0" max="0.5" value="' + this.constants.physics.repulsion.springConstant + '" step="0.001" style="width:300px" id="graph_R_sc"></td><td>0.5</td><td><input value="' + this.constants.physics.repulsion.springConstant + '" id="graph_R_sc_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">damping</td><td>0</td><td><input type="range" min="0" max="0.3" value="' + this.constants.physics.repulsion.damping + '" step="0.005" style="width:300px" id="graph_R_damp"></td><td>0.3</td><td><input value="' + this.constants.physics.repulsion.damping + '" id="graph_R_damp_value" style="width:60px"></td>' + '</tr>' + '</table>' + '<table id="graph_H_table" style="display:none">' + '<tr><td width="150"><b>Hierarchical</b></td></tr>' + '<tr>' + '<td width="150px">nodeDistance</td><td>0</td><td><input type="range" min="0" max="300" value="' + this.constants.physics.hierarchicalRepulsion.nodeDistance + '" step="1" style="width:300px" id="graph_H_nd"></td><td width="50px">300</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.nodeDistance + '" id="graph_H_nd_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">centralGravity</td><td>0</td><td><input type="range" min="0" max="3" value="' + this.constants.physics.hierarchicalRepulsion.centralGravity + '" step="0.05" style="width:300px" id="graph_H_cg"></td><td>3</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.centralGravity + '" id="graph_H_cg_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">springLength</td><td>0</td><td><input type="range" min="0" max="500" value="' + this.constants.physics.hierarchicalRepulsion.springLength + '" step="1" style="width:300px" id="graph_H_sl"></td><td>500</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.springLength + '" id="graph_H_sl_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">springConstant</td><td>0</td><td><input type="range" min="0" max="0.5" value="' + this.constants.physics.hierarchicalRepulsion.springConstant + '" step="0.001" style="width:300px" id="graph_H_sc"></td><td>0.5</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.springConstant + '" id="graph_H_sc_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">damping</td><td>0</td><td><input type="range" min="0" max="0.3" value="' + this.constants.physics.hierarchicalRepulsion.damping + '" step="0.005" style="width:300px" id="graph_H_damp"></td><td>0.3</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.damping + '" id="graph_H_damp_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">direction</td><td>1</td><td><input type="range" min="0" max="3" value="' + hierarchicalLayoutDirections.indexOf(this.constants.hierarchicalLayout.direction) + '" step="1" style="width:300px" id="graph_H_direction"></td><td>4</td><td><input value="' + this.constants.hierarchicalLayout.direction + '" id="graph_H_direction_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">levelSeparation</td><td>1</td><td><input type="range" min="0" max="500" value="' + this.constants.hierarchicalLayout.levelSeparation + '" step="1" style="width:300px" id="graph_H_levsep"></td><td>500</td><td><input value="' + this.constants.hierarchicalLayout.levelSeparation + '" id="graph_H_levsep_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">nodeSpacing</td><td>1</td><td><input type="range" min="0" max="500" value="' + this.constants.hierarchicalLayout.nodeSpacing + '" step="1" style="width:300px" id="graph_H_nspac"></td><td>500</td><td><input value="' + this.constants.hierarchicalLayout.nodeSpacing + '" id="graph_H_nspac_value" style="width:60px"></td>' + '</tr>' + '</table>' + '<table><tr><td><b>Options:</b></td></tr>' + '<tr>' + '<td width="180px"><input type="button" id="graph_toggleSmooth" value="Toggle smoothCurves" style="width:150px"></td>' + '<td width="180px"><input type="button" id="graph_repositionNodes" value="Reinitialize" style="width:150px"></td>' + '<td width="180px"><input type="button" id="graph_generateOptions" value="Generate Options" style="width:150px"></td>' + '</tr>' + '</table>' this.containerElement.parentElement.insertBefore(this.physicsConfiguration, this.containerElement); this.optionsDiv = document.createElement("div"); this.optionsDiv.style.fontSize = "14px"; this.optionsDiv.style.fontFamily = "verdana"; this.containerElement.parentElement.insertBefore(this.optionsDiv, this.containerElement); var rangeElement; rangeElement = document.getElementById('graph_BH_gc'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_gc', -1, "physics_barnesHut_gravitationalConstant"); rangeElement = document.getElementById('graph_BH_cg'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_cg', 1, "physics_centralGravity"); rangeElement = document.getElementById('graph_BH_sc'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sc', 1, "physics_springConstant"); rangeElement = document.getElementById('graph_BH_sl'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sl', 1, "physics_springLength"); rangeElement = document.getElementById('graph_BH_damp'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_damp', 1, "physics_damping"); rangeElement = document.getElementById('graph_R_nd'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_nd', 1, "physics_repulsion_nodeDistance"); rangeElement = document.getElementById('graph_R_cg'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_cg', 1, "physics_centralGravity"); rangeElement = document.getElementById('graph_R_sc'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sc', 1, "physics_springConstant"); rangeElement = document.getElementById('graph_R_sl'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sl', 1, "physics_springLength"); rangeElement = document.getElementById('graph_R_damp'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_damp', 1, "physics_damping"); rangeElement = document.getElementById('graph_H_nd'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nd', 1, "physics_hierarchicalRepulsion_nodeDistance"); rangeElement = document.getElementById('graph_H_cg'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_cg', 1, "physics_centralGravity"); rangeElement = document.getElementById('graph_H_sc'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sc', 1, "physics_springConstant"); rangeElement = document.getElementById('graph_H_sl'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sl', 1, "physics_springLength"); rangeElement = document.getElementById('graph_H_damp'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_damp', 1, "physics_damping"); rangeElement = document.getElementById('graph_H_direction'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_direction', hierarchicalLayoutDirections, "hierarchicalLayout_direction"); rangeElement = document.getElementById('graph_H_levsep'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_levsep', 1, "hierarchicalLayout_levelSeparation"); rangeElement = document.getElementById('graph_H_nspac'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nspac', 1, "hierarchicalLayout_nodeSpacing"); var radioButton1 = document.getElementById("graph_physicsMethod1"); var radioButton2 = document.getElementById("graph_physicsMethod2"); var radioButton3 = document.getElementById("graph_physicsMethod3"); radioButton2.checked = true; if (this.constants.physics.barnesHut.enabled) { radioButton1.checked = true; } if (this.constants.hierarchicalLayout.enabled) { radioButton3.checked = true; } var graph_toggleSmooth = document.getElementById("graph_toggleSmooth"); var graph_repositionNodes = document.getElementById("graph_repositionNodes"); var graph_generateOptions = document.getElementById("graph_generateOptions"); graph_toggleSmooth.onclick = graphToggleSmoothCurves.bind(this); graph_repositionNodes.onclick = graphRepositionNodes.bind(this); graph_generateOptions.onclick = graphGenerateOptions.bind(this); if (this.constants.smoothCurves == true && this.constants.dynamicSmoothCurves == false) { graph_toggleSmooth.style.background = "#A4FF56"; } else { graph_toggleSmooth.style.background = "#FF8532"; } switchConfigurations.apply(this); radioButton1.onchange = switchConfigurations.bind(this); radioButton2.onchange = switchConfigurations.bind(this); radioButton3.onchange = switchConfigurations.bind(this); } }; /** * This overwrites the this.constants. * * @param constantsVariableName * @param value * @private */ exports._overWriteGraphConstants = function (constantsVariableName, value) { var nameArray = constantsVariableName.split("_"); if (nameArray.length == 1) { this.constants[nameArray[0]] = value; } else if (nameArray.length == 2) { this.constants[nameArray[0]][nameArray[1]] = value; } else if (nameArray.length == 3) { this.constants[nameArray[0]][nameArray[1]][nameArray[2]] = value; } }; /** * this function is bound to the toggle smooth curves button. That is also why it is not in the prototype. */ function graphToggleSmoothCurves () { this.constants.smoothCurves.enabled = !this.constants.smoothCurves.enabled; var graph_toggleSmooth = document.getElementById("graph_toggleSmooth"); if (this.constants.smoothCurves.enabled == true) {graph_toggleSmooth.style.background = "#A4FF56";} else {graph_toggleSmooth.style.background = "#FF8532";} this._configureSmoothCurves(false); } /** * this function is used to scramble the nodes * */ function graphRepositionNodes () { for (var nodeId in this.calculationNodes) { if (this.calculationNodes.hasOwnProperty(nodeId)) { this.calculationNodes[nodeId].vx = 0; this.calculationNodes[nodeId].vy = 0; this.calculationNodes[nodeId].fx = 0; this.calculationNodes[nodeId].fy = 0; } } if (this.constants.hierarchicalLayout.enabled == true) { this._setupHierarchicalLayout(); showValueOfRange.call(this, 'graph_H_nd', 1, "physics_hierarchicalRepulsion_nodeDistance"); showValueOfRange.call(this, 'graph_H_cg', 1, "physics_centralGravity"); showValueOfRange.call(this, 'graph_H_sc', 1, "physics_springConstant"); showValueOfRange.call(this, 'graph_H_sl', 1, "physics_springLength"); showValueOfRange.call(this, 'graph_H_damp', 1, "physics_damping"); } else { this.repositionNodes(); } this.moving = true; this.start(); } /** * this is used to generate an options file from the playing with physics system. */ function graphGenerateOptions () { var options = "No options are required, default values used."; var optionsSpecific = []; var radioButton1 = document.getElementById("graph_physicsMethod1"); var radioButton2 = document.getElementById("graph_physicsMethod2"); if (radioButton1.checked == true) { if (this.constants.physics.barnesHut.gravitationalConstant != this.backupConstants.physics.barnesHut.gravitationalConstant) {optionsSpecific.push("gravitationalConstant: " + this.constants.physics.barnesHut.gravitationalConstant);} if (this.constants.physics.centralGravity != this.backupConstants.physics.barnesHut.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);} if (this.constants.physics.springLength != this.backupConstants.physics.barnesHut.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);} if (this.constants.physics.springConstant != this.backupConstants.physics.barnesHut.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);} if (this.constants.physics.damping != this.backupConstants.physics.barnesHut.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);} if (optionsSpecific.length != 0) { options = "var options = {"; options += "physics: {barnesHut: {"; for (var i = 0; i < optionsSpecific.length; i++) { options += optionsSpecific[i]; if (i < optionsSpecific.length - 1) { options += ", " } } options += '}}' } if (this.constants.smoothCurves.enabled != this.backupConstants.smoothCurves.enabled) { if (optionsSpecific.length == 0) {options = "var options = {";} else {options += ", "} options += "smoothCurves: " + this.constants.smoothCurves.enabled; } if (options != "No options are required, default values used.") { options += '};' } } else if (radioButton2.checked == true) { options = "var options = {"; options += "physics: {barnesHut: {enabled: false}"; if (this.constants.physics.repulsion.nodeDistance != this.backupConstants.physics.repulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.repulsion.nodeDistance);} if (this.constants.physics.centralGravity != this.backupConstants.physics.repulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);} if (this.constants.physics.springLength != this.backupConstants.physics.repulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);} if (this.constants.physics.springConstant != this.backupConstants.physics.repulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);} if (this.constants.physics.damping != this.backupConstants.physics.repulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);} if (optionsSpecific.length != 0) { options += ", repulsion: {"; for (var i = 0; i < optionsSpecific.length; i++) { options += optionsSpecific[i]; if (i < optionsSpecific.length - 1) { options += ", " } } options += '}}' } if (optionsSpecific.length == 0) {options += "}"} if (this.constants.smoothCurves != this.backupConstants.smoothCurves) { options += ", smoothCurves: " + this.constants.smoothCurves; } options += '};' } else { options = "var options = {"; if (this.constants.physics.hierarchicalRepulsion.nodeDistance != this.backupConstants.physics.hierarchicalRepulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.hierarchicalRepulsion.nodeDistance);} if (this.constants.physics.centralGravity != this.backupConstants.physics.hierarchicalRepulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);} if (this.constants.physics.springLength != this.backupConstants.physics.hierarchicalRepulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);} if (this.constants.physics.springConstant != this.backupConstants.physics.hierarchicalRepulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);} if (this.constants.physics.damping != this.backupConstants.physics.hierarchicalRepulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);} if (optionsSpecific.length != 0) { options += "physics: {hierarchicalRepulsion: {"; for (var i = 0; i < optionsSpecific.length; i++) { options += optionsSpecific[i]; if (i < optionsSpecific.length - 1) { options += ", "; } } options += '}},'; } options += 'hierarchicalLayout: {'; optionsSpecific = []; if (this.constants.hierarchicalLayout.direction != this.backupConstants.hierarchicalLayout.direction) {optionsSpecific.push("direction: " + this.constants.hierarchicalLayout.direction);} if (Math.abs(this.constants.hierarchicalLayout.levelSeparation) != this.backupConstants.hierarchicalLayout.levelSeparation) {optionsSpecific.push("levelSeparation: " + this.constants.hierarchicalLayout.levelSeparation);} if (this.constants.hierarchicalLayout.nodeSpacing != this.backupConstants.hierarchicalLayout.nodeSpacing) {optionsSpecific.push("nodeSpacing: " + this.constants.hierarchicalLayout.nodeSpacing);} if (optionsSpecific.length != 0) { for (var i = 0; i < optionsSpecific.length; i++) { options += optionsSpecific[i]; if (i < optionsSpecific.length - 1) { options += ", " } } options += '}' } else { options += "enabled:true}"; } options += '};' } this.optionsDiv.innerHTML = options; } /** * this is used to switch between barnesHut, repulsion and hierarchical. * */ function switchConfigurations () { var ids = ["graph_BH_table", "graph_R_table", "graph_H_table"]; var radioButton = document.querySelector('input[name="graph_physicsMethod"]:checked').value; var tableId = "graph_" + radioButton + "_table"; var table = document.getElementById(tableId); table.style.display = "block"; for (var i = 0; i < ids.length; i++) { if (ids[i] != tableId) { table = document.getElementById(ids[i]); table.style.display = "none"; } } this._restoreNodes(); if (radioButton == "R") { this.constants.hierarchicalLayout.enabled = false; this.constants.physics.hierarchicalRepulsion.enabled = false; this.constants.physics.barnesHut.enabled = false; } else if (radioButton == "H") { if (this.constants.hierarchicalLayout.enabled == false) { this.constants.hierarchicalLayout.enabled = true; this.constants.physics.hierarchicalRepulsion.enabled = true; this.constants.physics.barnesHut.enabled = false; this.constants.smoothCurves.enabled = false; this._setupHierarchicalLayout(); } } else { this.constants.hierarchicalLayout.enabled = false; this.constants.physics.hierarchicalRepulsion.enabled = false; this.constants.physics.barnesHut.enabled = true; } this._loadSelectedForceSolver(); var graph_toggleSmooth = document.getElementById("graph_toggleSmooth"); if (this.constants.smoothCurves.enabled == true) {graph_toggleSmooth.style.background = "#A4FF56";} else {graph_toggleSmooth.style.background = "#FF8532";} this.moving = true; this.start(); } /** * this generates the ranges depending on the iniital values. * * @param id * @param map * @param constantsVariableName */ function showValueOfRange (id,map,constantsVariableName) { var valueId = id + "_value"; var rangeValue = document.getElementById(id).value; if (map instanceof Array) { document.getElementById(valueId).value = map[parseInt(rangeValue)]; this._overWriteGraphConstants(constantsVariableName,map[parseInt(rangeValue)]); } else { document.getElementById(valueId).value = parseInt(map) * parseFloat(rangeValue); this._overWriteGraphConstants(constantsVariableName, parseInt(map) * parseFloat(rangeValue)); } if (constantsVariableName == "hierarchicalLayout_direction" || constantsVariableName == "hierarchicalLayout_levelSeparation" || constantsVariableName == "hierarchicalLayout_nodeSpacing") { this._setupHierarchicalLayout(); } this.moving = true; this.start(); } /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { function webpackContext(req) { throw new Error("Cannot find module '" + req + "'."); } webpackContext.resolve = webpackContext; webpackContext.keys = function() { return []; }; module.exports = webpackContext; /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { module.exports = function(module) { if(!module.webpackPolyfill) { module.deprecate = function() {}; module.paths = []; // module.parent = undefined by default module.children = []; module.webpackPolyfill = 1; } return module; } /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { /** * Calculate the forces the nodes apply on each other based on a repulsion field. * This field is linearly approximated. * * @private */ exports._calculateNodeForces = function () { var dx, dy, angle, distance, fx, fy, combinedClusterSize, repulsingForce, node1, node2, i, j; var nodes = this.calculationNodes; var nodeIndices = this.calculationNodeIndices; // approximation constants var a_base = -2 / 3; var b = 4 / 3; // repulsing forces between nodes var nodeDistance = this.constants.physics.repulsion.nodeDistance; var minimumDistance = nodeDistance; // we loop from i over all but the last entree in the array // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j for (i = 0; i < nodeIndices.length - 1; i++) { node1 = nodes[nodeIndices[i]]; for (j = i + 1; j < nodeIndices.length; j++) { node2 = nodes[nodeIndices[j]]; combinedClusterSize = node1.clusterSize + node2.clusterSize - 2; dx = node2.x - node1.x; dy = node2.y - node1.y; distance = Math.sqrt(dx * dx + dy * dy); minimumDistance = (combinedClusterSize == 0) ? nodeDistance : (nodeDistance * (1 + combinedClusterSize * this.constants.clustering.distanceAmplification)); var a = a_base / minimumDistance; if (distance < 2 * minimumDistance) { if (distance < 0.5 * minimumDistance) { repulsingForce = 1.0; } else { repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)) } // amplify the repulsion for clusters. repulsingForce *= (combinedClusterSize == 0) ? 1 : 1 + combinedClusterSize * this.constants.clustering.forceAmplification; repulsingForce = repulsingForce / distance; fx = dx * repulsingForce; fy = dy * repulsingForce; node1.fx -= fx; node1.fy -= fy; node2.fx += fx; node2.fy += fy; } } } }; /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { /** * Calculate the forces the nodes apply on eachother based on a repulsion field. * This field is linearly approximated. * * @private */ exports._calculateNodeForces = function () { var dx, dy, distance, fx, fy, repulsingForce, node1, node2, i, j; var nodes = this.calculationNodes; var nodeIndices = this.calculationNodeIndices; // repulsing forces between nodes var nodeDistance = this.constants.physics.hierarchicalRepulsion.nodeDistance; // we loop from i over all but the last entree in the array // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j for (i = 0; i < nodeIndices.length - 1; i++) { node1 = nodes[nodeIndices[i]]; for (j = i + 1; j < nodeIndices.length; j++) { node2 = nodes[nodeIndices[j]]; // nodes only affect nodes on their level if (node1.level == node2.level) { dx = node2.x - node1.x; dy = node2.y - node1.y; distance = Math.sqrt(dx * dx + dy * dy); var steepness = 0.05; if (distance < nodeDistance) { repulsingForce = -Math.pow(steepness*distance,2) + Math.pow(steepness*nodeDistance,2); } else { repulsingForce = 0; } // normalize force with if (distance == 0) { distance = 0.01; } else { repulsingForce = repulsingForce / distance; } fx = dx * repulsingForce; fy = dy * repulsingForce; node1.fx -= fx; node1.fy -= fy; node2.fx += fx; node2.fy += fy; } } } }; /** * this function calculates the effects of the springs in the case of unsmooth curves. * * @private */ exports._calculateHierarchicalSpringForces = function () { var edgeLength, edge, edgeId; var dx, dy, fx, fy, springForce, distance; var edges = this.edges; var nodes = this.calculationNodes; var nodeIndices = this.calculationNodeIndices; for (var i = 0; i < nodeIndices.length; i++) { var node1 = nodes[nodeIndices[i]]; node1.springFx = 0; node1.springFy = 0; } // forces caused by the edges, modelled as springs for (edgeId in edges) { if (edges.hasOwnProperty(edgeId)) { edge = edges[edgeId]; if (edge.connected) { // only calculate forces if nodes are in the same sector if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) { edgeLength = edge.physics.springLength; // this implies that the edges between big clusters are longer edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth; dx = (edge.from.x - edge.to.x); dy = (edge.from.y - edge.to.y); distance = Math.sqrt(dx * dx + dy * dy); if (distance == 0) { distance = 0.01; } // the 1/distance is so the fx and fy can be calculated without sine or cosine. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance; fx = dx * springForce; fy = dy * springForce; if (edge.to.level != edge.from.level) { edge.to.springFx -= fx; edge.to.springFy -= fy; edge.from.springFx += fx; edge.from.springFy += fy; } else { var factor = 0.5; edge.to.fx -= factor*fx; edge.to.fy -= factor*fy; edge.from.fx += factor*fx; edge.from.fy += factor*fy; } } } } } // normalize spring forces var springForce = 1; var springFx, springFy; for (i = 0; i < nodeIndices.length; i++) { var node = nodes[nodeIndices[i]]; springFx = Math.min(springForce,Math.max(-springForce,node.springFx)); springFy = Math.min(springForce,Math.max(-springForce,node.springFy)); node.fx += springFx; node.fy += springFy; } // retain energy balance var totalFx = 0; var totalFy = 0; for (i = 0; i < nodeIndices.length; i++) { var node = nodes[nodeIndices[i]]; totalFx += node.fx; totalFy += node.fy; } var correctionFx = totalFx / nodeIndices.length; var correctionFy = totalFy / nodeIndices.length; for (i = 0; i < nodeIndices.length; i++) { var node = nodes[nodeIndices[i]]; node.fx -= correctionFx; node.fy -= correctionFy; } }; /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { /** * This function calculates the forces the nodes apply on eachother based on a gravitational model. * The Barnes Hut method is used to speed up this N-body simulation. * * @private */ exports._calculateNodeForces = function() { if (this.constants.physics.barnesHut.gravitationalConstant != 0) { var node; var nodes = this.calculationNodes; var nodeIndices = this.calculationNodeIndices; var nodeCount = nodeIndices.length; this._formBarnesHutTree(nodes,nodeIndices); var barnesHutTree = this.barnesHutTree; // place the nodes one by one recursively for (var i = 0; i < nodeCount; i++) { node = nodes[nodeIndices[i]]; if (node.options.mass > 0) { // starting with root is irrelevant, it never passes the BarnesHut condition this._getForceContribution(barnesHutTree.root.children.NW,node); this._getForceContribution(barnesHutTree.root.children.NE,node); this._getForceContribution(barnesHutTree.root.children.SW,node); this._getForceContribution(barnesHutTree.root.children.SE,node); } } } }; /** * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass. * If a region contains a single node, we check if it is not itself, then we apply the force. * * @param parentBranch * @param node * @private */ exports._getForceContribution = function(parentBranch,node) { // we get no force contribution from an empty region if (parentBranch.childrenCount > 0) { var dx,dy,distance; // get the distance from the center of mass to the node. dx = parentBranch.centerOfMass.x - node.x; dy = parentBranch.centerOfMass.y - node.y; distance = Math.sqrt(dx * dx + dy * dy); // BarnesHut condition // original condition : s/d < theta = passed === d/s > 1/theta = passed // calcSize = 1/s --> d * 1/s > 1/theta = passed if (distance * parentBranch.calcSize > this.constants.physics.barnesHut.theta) { // duplicate code to reduce function calls to speed up program if (distance == 0) { distance = 0.1*Math.random(); dx = distance; } var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.options.mass / (distance * distance * distance); var fx = dx * gravityForce; var fy = dy * gravityForce; node.fx += fx; node.fy += fy; } else { // Did not pass the condition, go into children if available if (parentBranch.childrenCount == 4) { this._getForceContribution(parentBranch.children.NW,node); this._getForceContribution(parentBranch.children.NE,node); this._getForceContribution(parentBranch.children.SW,node); this._getForceContribution(parentBranch.children.SE,node); } else { // parentBranch must have only one node, if it was empty we wouldnt be here if (parentBranch.children.data.id != node.id) { // if it is not self // duplicate code to reduce function calls to speed up program if (distance == 0) { distance = 0.5*Math.random(); dx = distance; } var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.options.mass / (distance * distance * distance); var fx = dx * gravityForce; var fy = dy * gravityForce; node.fx += fx; node.fy += fy; } } } } }; /** * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes. * * @param nodes * @param nodeIndices * @private */ exports._formBarnesHutTree = function(nodes,nodeIndices) { var node; var nodeCount = nodeIndices.length; var minX = Number.MAX_VALUE, minY = Number.MAX_VALUE, maxX =-Number.MAX_VALUE, maxY =-Number.MAX_VALUE; // get the range of the nodes for (var i = 0; i < nodeCount; i++) { var x = nodes[nodeIndices[i]].x; var y = nodes[nodeIndices[i]].y; if (nodes[nodeIndices[i]].options.mass > 0) { if (x < minX) { minX = x; } if (x > maxX) { maxX = x; } if (y < minY) { minY = y; } if (y > maxY) { maxY = y; } } } // make the range a square var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y if (sizeDiff > 0) {minY -= 0.5 * sizeDiff; maxY += 0.5 * sizeDiff;} // xSize > ySize else {minX += 0.5 * sizeDiff; maxX -= 0.5 * sizeDiff;} // xSize < ySize var minimumTreeSize = 1e-5; var rootSize = Math.max(minimumTreeSize,Math.abs(maxX - minX)); var halfRootSize = 0.5 * rootSize; var centerX = 0.5 * (minX + maxX), centerY = 0.5 * (minY + maxY); // construct the barnesHutTree var barnesHutTree = { root:{ centerOfMass: {x:0, y:0}, mass:0, range: { minX: centerX-halfRootSize,maxX:centerX+halfRootSize, minY: centerY-halfRootSize,maxY:centerY+halfRootSize }, size: rootSize, calcSize: 1 / rootSize, children: { data:null}, maxWidth: 0, level: 0, childrenCount: 4 } }; this._splitBranch(barnesHutTree.root); // place the nodes one by one recursively for (i = 0; i < nodeCount; i++) { node = nodes[nodeIndices[i]]; if (node.options.mass > 0) { this._placeInTree(barnesHutTree.root,node); } } // make global this.barnesHutTree = barnesHutTree }; /** * this updates the mass of a branch. this is increased by adding a node. * * @param parentBranch * @param node * @private */ exports._updateBranchMass = function(parentBranch, node) { var totalMass = parentBranch.mass + node.options.mass; var totalMassInv = 1/totalMass; parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.options.mass; parentBranch.centerOfMass.x *= totalMassInv; parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.options.mass; parentBranch.centerOfMass.y *= totalMassInv; parentBranch.mass = totalMass; var biggestSize = Math.max(Math.max(node.height,node.radius),node.width); parentBranch.maxWidth = (parentBranch.maxWidth < biggestSize) ? biggestSize : parentBranch.maxWidth; }; /** * determine in which branch the node will be placed. * * @param parentBranch * @param node * @param skipMassUpdate * @private */ exports._placeInTree = function(parentBranch,node,skipMassUpdate) { if (skipMassUpdate != true || skipMassUpdate === undefined) { // update the mass of the branch. this._updateBranchMass(parentBranch,node); } if (parentBranch.children.NW.range.maxX > node.x) { // in NW or SW if (parentBranch.children.NW.range.maxY > node.y) { // in NW this._placeInRegion(parentBranch,node,"NW"); } else { // in SW this._placeInRegion(parentBranch,node,"SW"); } } else { // in NE or SE if (parentBranch.children.NW.range.maxY > node.y) { // in NE this._placeInRegion(parentBranch,node,"NE"); } else { // in SE this._placeInRegion(parentBranch,node,"SE"); } } }; /** * actually place the node in a region (or branch) * * @param parentBranch * @param node * @param region * @private */ exports._placeInRegion = function(parentBranch,node,region) { switch (parentBranch.children[region].childrenCount) { case 0: // place node here parentBranch.children[region].children.data = node; parentBranch.children[region].childrenCount = 1; this._updateBranchMass(parentBranch.children[region],node); break; case 1: // convert into children // if there are two nodes exactly overlapping (on init, on opening of cluster etc.) // we move one node a pixel and we do not put it in the tree. if (parentBranch.children[region].children.data.x == node.x && parentBranch.children[region].children.data.y == node.y) { node.x += Math.random(); node.y += Math.random(); } else { this._splitBranch(parentBranch.children[region]); this._placeInTree(parentBranch.children[region],node); } break; case 4: // place in branch this._placeInTree(parentBranch.children[region],node); break; } }; /** * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch * after the split is complete. * * @param parentBranch * @private */ exports._splitBranch = function(parentBranch) { // if the branch is shaded with a node, replace the node in the new subset. var containedNode = null; if (parentBranch.childrenCount == 1) { containedNode = parentBranch.children.data; parentBranch.mass = 0; parentBranch.centerOfMass.x = 0; parentBranch.centerOfMass.y = 0; } parentBranch.childrenCount = 4; parentBranch.children.data = null; this._insertRegion(parentBranch,"NW"); this._insertRegion(parentBranch,"NE"); this._insertRegion(parentBranch,"SW"); this._insertRegion(parentBranch,"SE"); if (containedNode != null) { this._placeInTree(parentBranch,containedNode); } }; /** * This function subdivides the region into four new segments. * Specifically, this inserts a single new segment. * It fills the children section of the parentBranch * * @param parentBranch * @param region * @param parentRange * @private */ exports._insertRegion = function(parentBranch, region) { var minX,maxX,minY,maxY; var childSize = 0.5 * parentBranch.size; switch (region) { case "NW": minX = parentBranch.range.minX; maxX = parentBranch.range.minX + childSize; minY = parentBranch.range.minY; maxY = parentBranch.range.minY + childSize; break; case "NE": minX = parentBranch.range.minX + childSize; maxX = parentBranch.range.maxX; minY = parentBranch.range.minY; maxY = parentBranch.range.minY + childSize; break; case "SW": minX = parentBranch.range.minX; maxX = parentBranch.range.minX + childSize; minY = parentBranch.range.minY + childSize; maxY = parentBranch.range.maxY; break; case "SE": minX = parentBranch.range.minX + childSize; maxX = parentBranch.range.maxX; minY = parentBranch.range.minY + childSize; maxY = parentBranch.range.maxY; break; } parentBranch.children[region] = { centerOfMass:{x:0,y:0}, mass:0, range:{minX:minX,maxX:maxX,minY:minY,maxY:maxY}, size: 0.5 * parentBranch.size, calcSize: 2 * parentBranch.calcSize, children: {data:null}, maxWidth: 0, level: parentBranch.level+1, childrenCount: 0 }; }; /** * This function is for debugging purposed, it draws the tree. * * @param ctx * @param color * @private */ exports._drawTree = function(ctx,color) { if (this.barnesHutTree !== undefined) { ctx.lineWidth = 1; this._drawBranch(this.barnesHutTree.root,ctx,color); } }; /** * This function is for debugging purposes. It draws the branches recursively. * * @param branch * @param ctx * @param color * @private */ exports._drawBranch = function(branch,ctx,color) { if (color === undefined) { color = "#FF0000"; } if (branch.childrenCount == 4) { this._drawBranch(branch.children.NW,ctx); this._drawBranch(branch.children.NE,ctx); this._drawBranch(branch.children.SE,ctx); this._drawBranch(branch.children.SW,ctx); } ctx.strokeStyle = color; ctx.beginPath(); ctx.moveTo(branch.range.minX,branch.range.minY); ctx.lineTo(branch.range.maxX,branch.range.minY); ctx.stroke(); ctx.beginPath(); ctx.moveTo(branch.range.maxX,branch.range.minY); ctx.lineTo(branch.range.maxX,branch.range.maxY); ctx.stroke(); ctx.beginPath(); ctx.moveTo(branch.range.maxX,branch.range.maxY); ctx.lineTo(branch.range.minX,branch.range.maxY); ctx.stroke(); ctx.beginPath(); ctx.moveTo(branch.range.minX,branch.range.maxY); ctx.lineTo(branch.range.minX,branch.range.minY); ctx.stroke(); /* if (branch.mass > 0) { ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass); ctx.stroke(); } */ }; /***/ } /******/ ]) });
__tests__/common.js
react-armenia/react-native-view-editable
import React from 'react'; import { generateArray } from '../lib/utils'; describe('Common utils', () => { describe('generateArray', () => { it('should generate array for given range', () => { const arr = generateArray(360); expect(arr.length).toBe(360); expect(arr).toMatchSnapshot(); }); }); });
plugins/home/test/index.spec.js
takfukuda917/history
const tape = require('tape-catch'); tape('Verify / route', { skip: false }, (describe) => { const hapi = require('hapi'); const hapiReactViews = require('hapi-react-views'); const inert = require('inert'); const path = require('path'); const vision = require('vision'); require('babel-core/register')({ presets: ['react', 'es2015'], }); const lib = require('../lib'); const utils = require('../../utils/lib'); const plugins = [inert, vision, lib]; const port = utils.config.get('port'); describe.test('* Valid React.js view', { skip: false }, (assert) => { const server = new hapi.Server(); server.connection({ port }); server.register(plugins, (pluginError) => { if (pluginError) { return assert.fail(pluginError); } const url = '/'; const request = { method: 'GET', url, }; server.views({ engines: { jsx: hapiReactViews, }, relativeTo: path.join(__dirname, '../../../'), }); return server.inject(request, (response) => { assert.ok(response.result.indexOf('<a href="static/gallery-demo/xml/gallery.xml">demo</a>') > -1, 'Link to demo gallery'); assert.end(); }); }); }); });
src/components/common/svg-icons/editor/format-underlined.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFormatUnderlined = (props) => ( <SvgIcon {...props}> <path d="M12 17c3.31 0 6-2.69 6-6V3h-2.5v8c0 1.93-1.57 3.5-3.5 3.5S8.5 12.93 8.5 11V3H6v8c0 3.31 2.69 6 6 6zm-7 2v2h14v-2H5z"/> </SvgIcon> ); EditorFormatUnderlined = pure(EditorFormatUnderlined); EditorFormatUnderlined.displayName = 'EditorFormatUnderlined'; EditorFormatUnderlined.muiName = 'SvgIcon'; export default EditorFormatUnderlined;
src/routes/Timetable/components/Timetable/Timetable.js
BloomerWD/timetable
import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { browserHistory } from 'react-router'; import { getUserDataFromLocalStorage, getUserTimetablesFromLocalStorage } from '../../../../utils/localData'; import { incrementWeek, decrementWeek, getSchedules } from '../../modules/timetable'; import TimetableList from '../TimetableList'; class Timetable extends Component { constructor(props) { super(props); this.state = { isLoadingTimetable: true, listTimetables: getUserTimetablesFromLocalStorage(), current: { date: this.props.date.current.date } } if (this.state.listTimetables.length < 1) { browserHistory.push('/user'); } this.goToSetting = this.goToSetting.bind(this); this.handleClickOnCalendarItem = this.handleClickOnCalendarItem.bind(this); } componentDidMount() { this.props.getSchedules({from: this.props.date.from, to: this.props.date.to}, () => { this.setState({ isLoadingTimetable: false }); }); setTimeout(() => { if (this.calendarActiveItem) { this.calendarBox.scrollTop = this.calendarActiveItem.getBoundingClientRect().top - this.calendarBox.offsetHeight / 2; } }, 1); } goToSetting() { browserHistory.push('/user'); } handleClickOnCalendarItem(e) { if (e.target.getAttribute('data-from') === this.state.current.date) return; this.setState({ isLoadingTimetable: true }); this.props.getSchedules({from: e.target.getAttribute('data-from'), to: e.target.getAttribute('data-to')},() => { this.setState({ isLoadingTimetable: false }); }); this.setState({ current: { date: e.target.getAttribute('data-from') } }); } renderCalendar() { let i = 0; return this.props.calendar.map(item => { i++; return ( <li key={i} className={item.from == this.state.current.date ? `calendar_list__item active` : `calendar_list__item`} ref={li => {item.from == this.state.current.date ? this.calendarActiveItem = li : null}}> <div className="clickable_btn" data-from={item.from} data-to={item.to} onClick={this.handleClickOnCalendarItem}></div> {item.day} <div className="calendar_list__item__month_and_daystr"> {`${item.month}, ${item.dayStr}`} </div> </li> ) }) } renderTimetable() { if (this.state.isLoadingTimetable) { return ( <div className="loading_box"> <span className="icon-circular-graph"></span> </div> ); } return <TimetableList list={this.props.timetables} />; } render() { if (this.state.listTimetables.length < 1) return null return ( <div> <div className="header_wrapper"> <div className="btn_header calendar" onClick={this.props.decrementWeek} ><span className="icon-chevron-up"></span></div> <h1 className="group_title">Расписание</h1> <div className="btn_header" onClick={this.goToSetting}> <span className="icon-cog"></span> </div> </div> <div className="main_wrapper"> <div className="calendar_wrapper"> <div className="calendar_list_wrapper"> <div className="calendar_list_content" ref={div => {this.calendarBox = div}}> <ul className="calendar_list"> {this.renderCalendar()} </ul> </div> </div> <div className="calendar__btn_choose" onClick={this.props.incrementWeek} ><span className="icon-chevron-down"></span></div> </div> <div className="content_wrapper"> {this.renderTimetable()} </div> </div> </div> ); } } Timetable.propTypes = { } const mapStateToProps = (state) => ({ calendar: state.timetable.calendar, date: state.timetable.date, timetables: state.timetable.timetables }); const mapDispatchToProps = { incrementWeek, decrementWeek, getSchedules } export default connect(mapStateToProps, mapDispatchToProps)(Timetable);
test/components/Footer.spec.js
Byte-Code/lm-digitalstore
import React from 'react'; import { shallow } from 'enzyme'; import Footer from '../../app/components/Footer'; describe('Footer', () => { it('should render properly', () => { const result = shallow(<Footer />); expect(result).toMatchSnapshot(); }); });
src/icons/favorite_icon.js
camboio/ibis
import React from 'react'; export default function FavoriteIcon(props){ return( <svg className={props.className} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 294.9 254.5"> <path className="st0" d="M140.9 244.8l-97.3-93.9C42.3 149.8 8 118.4 8 81 8 35.3 35.9 8 82.6 8c27.3 0 52.9 21.5 65.2 33.7C160.1 29.5 185.7 8 212.9 8c46.6 0 74.6 27.3 74.6 73 0 37.4-34.3 68.8-35.7 70.2l-97.2 93.6c-1.9 1.9-4.4 2.8-6.9 2.8-2.4 0-4.9-1-6.8-2.8z"/> </svg> ); }
shared/app/Tms/components/Remove/Remove.js
pebie/react-universally-node-config
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import classnames from 'classnames'; import Badge from '../Badge/Badge'; import Close from '../Icons/Close'; import styles from './Remove.scss'; /** * CardRemoveBtn * * Basic CardRemoveBtn component used to remove card of your personnal list * * @param {func} [onClickCrossButton] Action to dispatch to remove item */ export default class Remove extends Component { static propTypes = { onClick: PropTypes.func, position: PropTypes.string, }; static defaultProps = { onClick: () => {}, position: '', }; constructor(props) { super(props); this.profileId = 0; this.passToken = ''; } onClickCrossButton(event) { // Prevent other click if button overlay another view event.stopPropagation(); this.props.onClick(); } render() { return ( <div className={classnames(styles.remove, styles[`remove--${this.props.position}`])}> <Badge size="small"> <button className={styles['remove__remove-btn']} onClick={e => this.onClickCrossButton(e)} > <Close svgClass={styles['remove__remove-btn-svg']} /> </button> </Badge> </div> ); } }
ajax/libs/react-redux-form/1.0.0-beta.11/ReactReduxForm.js
wout/cdnjs
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("redux"),require("react-dom")):"function"==typeof define&&define.amd?define(["react","redux","react-dom"],t):"object"==typeof exports?exports.ReactReduxForm=t(require("react"),require("redux"),require("react-dom")):e.ReactReduxForm=t(e.React,e.Redux,e["react-dom"])}(this,function(e,t,r){return function(e){function t(n){if(r[n])return r[n].exports;var o=r[n]={exports:{},id:n,loaded:!1};return e[n].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){r(46),e.exports=r(46)},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r={BLUR:"rrf/blur",CHANGE:"rrf/change",FOCUS:"rrf/focus",RESET:"rrf/reset",VALIDATE:"rrf/validate",SET_DIRTY:"rrf/setDirty",SET_ERRORS:"rrf/setErrors",SET_INITIAL:"rrf/setInitial",SET_PENDING:"rrf/setPending",SET_PRISTINE:"rrf/setPristine",SET_SUBMITTED:"rrf/setSubmitted",SET_SUBMIT_FAILED:"rrf/setSubmitFailed",SET_TOUCHED:"rrf/setTouched",SET_UNTOUCHED:"rrf/setUntouched",SET_VALIDITY:"rrf/setValidity",SET_VALIDATING:"rrf/setValidating",SET_FIELDS_VALIDITY:"rrf/setFieldsValidity",SET_VIEW_VALUE:"rrf/setViewValue",RESET_VALIDITY:"rrf/resetValidity",BATCH:"rrf/batch",NULL:"rrf/null"};t["default"]=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){var n=t;return t.length?((0,f["default"])(n,".")?n=n.slice(0,-1):(0,f["default"])(n,"[]")&&(n=n.slice(0,-2)),(0,a["default"])(e,n,r)):e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(173),a=n(u),i=r(39),f=n(i)},function(e,t,r){function n(e){if(!a(e)||d.call(e)!=i||u(e))return!1;var t=o(e);if(null===t)return!0;var r=c.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&l.call(r)==s}var o=r(63),u=r(64),a=r(25),i="[object Object]",f=Object.prototype,l=Function.prototype.toString,c=f.hasOwnProperty,s=l.call(Object),d=f.toString;e.exports=n},function(e,t){"use strict";function r(e,t){var r={};return Object.keys(e||{}).forEach(function(n){r[n]=t(e[n],n,e)}),r}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)}function u(e,t,r,n){var u=t.length?(0,l["default"])(e,t,d.initialFieldState):e,a=u.hasOwnProperty("$form")?[].concat(o(t),["$form"]):t,f=(0,l["default"])(e,a,d.initialFieldState),c="function"==typeof r?r(f):r;if("$form"in u&&n){var p=(0,s["default"])(u,function(e,t){if("$form"===t)return i["default"].assign(f,c);var r="function"==typeof n?n(e,c):n;return i["default"].assign(e,r)});return t.length?i["default"].setIn(e,t,p):p}return i["default"].setIn(e,a,i["default"].assign(f,c))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=u;var a=r(9),i=n(a),f=r(2),l=n(f),c=r(4),s=n(c),d=r(7)},function(e,t){var r=Array.isArray;e.exports=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)}function u(e,t){return!t.length&&e.$form?e.$form:(0,d["default"])(e,t,Z)}function a(e,t){return e?e+"."+t:t}function i(e,t){var r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2],n=void 0;if(!(0,_["default"])(t)&&!(0,m["default"])(t))return v["default"].merge(Z,c({initialValue:t,value:t,model:e},r));n=(0,O["default"])(t,function(t,n){return i(a(e,n),t,r)});var o=v["default"].merge(Z,c({initialValue:t,value:t,model:e},r));return v["default"].set(n,"$form",o)}function f(e,t,r){return function(){var n=arguments.length<=0||void 0===arguments[0]?r:arguments[0],o=arguments[1];if(!o.model)return n;var u=(0,T["default"])(o.model);if(t.length&&!(0,y["default"])(u.slice(0,t.length),t))return n;var a=u.slice(t.length);return e(n,o,a)}}function l(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2],n=r.plugins,u=void 0===n?[]:n,a=r.initialFieldState,l=(0,T["default"])(e),c=i(e,t,a),s=u.concat(ee).map(function(e){return f(e,l,c)});return(0,x["default"])(E["default"].apply(void 0,o(s)))}Object.defineProperty(t,"__esModule",{value:!0}),t.initialFieldState=void 0;var c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e};t.getField=u,t["default"]=l;var s=r(2),d=n(s),p=r(9),v=n(p),h=r(47),y=n(h),b=r(3),m=n(b),g=r(6),_=n(g),P=r(4),O=n(P),j=r(19),T=n(j),S=r(96),E=n(S),M=r(29),x=n(M),w=r(84),k=n(w),V=r(91),A=n(V),C=r(88),I=n(C),F=r(85),D=n(F),R=r(90),N=n(R),$=r(89),U=n($),L=r(83),H=n(L),B=r(94),G=n(B),K=r(86),q=n(K),Y=r(93),W=n(Y),z=r(92),J=n(z),Q=r(87),X=n(Q),Z=t.initialFieldState={focus:!1,pending:!1,pristine:!0,submitted:!1,submitFailed:!1,retouched:!1,touched:!1,validating:!1,validated:!1,validity:{},errors:{}},ee=[D["default"],H["default"],G["default"],N["default"],U["default"],k["default"],A["default"],I["default"],q["default"],W["default"],J["default"],X["default"]]},function(t,r){t.exports=e},function(e,t,r){"use strict";function n(e){return null!==e&&(Array.isArray(e)||o(e))}function o(e){return"object"==typeof e&&e.constructor===Object&&Object.getPrototypeOf(e)===Object.prototype}function u(e){for(var t=0,r=e.length,n=Array(r);t<r;t+=1)n[t]=e[t];return n}function a(e){for(var t,r=0,n=Object.keys(e),o=n.length,u={};r<o;r+=1)t=n[r],u[t]=e[t];return u}function i(e){return Array.isArray(e)?u(e):a(e)}function f(e){return n(e)&&(!Object.isFrozen(e),!1)?c(e,[]):e}function l(e){return e}function c(e,t){if(t.some(function(t){return t===e}))throw new Error("object has a reference cycle");return Object.freeze(e),t.push(e),Object.keys(e).forEach(function(r){var o=e[r];n(o)&&c(o,t)}),t.pop(),e}function s(e,t){return(t||[]).reduce(function(e,t){if(e)return e[t]},e)}function d(e,t){return Object.keys(t).reduce(function(e,r){return b.assoc(e,r,t[r])},e)}function p(e,t,r){return null==e||null==t?e:Object.keys(t).reduce(function(e,o){var u=t[o],a=e[o],i=r?r(a,u,o):u;return n(u)&&n(a)?(Object.isFrozen(i)&&Object.isFrozen(a),i===a?e:Array.isArray(u)?b.assoc(e,o,i):v(e,o,p(a,i,r))):v(e,o,i)},e)}function v(e,t,r){return e[t]===r?e:b.assoc(e,t,r)}function h(e,t){var r=t||0,n=e.length;n-=r,n=n<0?0:n;for(var o=new Array(n),u=0;u<n;u+=1)o[u]=e[u+r];return o}function y(e){return h(e,1)}var b=t;t.freeze=function(e){return e},t.thaw=function g(e){if(n(e)&&Object.isFrozen(e)){var t=i(e);return Object.keys(t).forEach(function(e){t[e]=g(t[e])}),t}return e},t.assoc=function(e,t,r){if(e[t]===r)return l(e);var n=i(e);return n[t]=f(r),l(n)},t.set=t.assoc,t.dissoc=function(e,t){var r=i(e);return delete r[t],l(r)},t.unset=t.dissoc,t.assocIn=function _(e,t,r){var n=t[0];return 1===t.length?b.assoc(e,n,r):b.assoc(e,n,_(e[n]||{},t.slice(1),r))},t.setIn=t.assocIn,t.getIn=s,t.updateIn=function(e,t,r){var n=s(e,t);return b.assocIn(e,t,r(n))},["push","unshift","pop","shift","reverse","sort"].forEach(function(e){t[e]=function(t,r){var n=u(t);return n[e](f(r)),l(n)},t[e].displayName="icepick."+e}),t.splice=function(e){var t=u(e),r=y(arguments).map(f);return t.splice.apply(t,r),l(t)},t.slice=function(e,t,r){var n=e.slice(t,r);return l(n)},["map","filter"].forEach(function(e){t[e]=function(t,r){var n=r[e](t);return l(n)},t[e].displayName="icepick."+e}),t.extend=t.assign=function(){var e=y(arguments).reduce(d,arguments[0]);return l(e)},t.merge=p;var m={value:function(){return this.val},thru:function(e){return this.val=f(e(this.val)),this}};Object.keys(t).forEach(function(e){m[e]=function(){var r=h(arguments);return r.unshift(this.val),this.val=t[e].apply(null,r),this}}),t.chain=function(e){var t=Object.create(m);return t.val=e,t},t._weCareAbout=n,t._slice=h},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=r(43),a=n(u),i=r(73),f=n(i),l=r(42),c=n(l),s=o({},a["default"],f["default"],c["default"]);t["default"]=s},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){if(!e)return!0;if(!e.$form){var t=e.errors;return Array.isArray(t)||(0,a["default"])(t)?Object.keys(e.errors).every(function(t){var r=!e.errors[t];return r}):!t}return Object.keys(e).every(function(t){return o(e[t])})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(3),a=n(u)},function(e,t){"use strict";function r(e,t){return e===t?0!==e||1/e===1/t:e!==e&&t!==t}function n(e,t){var n=arguments.length<=2||void 0===arguments[2]?[]:arguments[2];if(r(e,t))return!0;if("object"!==("undefined"==typeof e?"undefined":u(e))||null===e||"object"!==("undefined"==typeof t?"undefined":u(t))||null===t)return!1;var o=Object.keys(e),i=Object.keys(t);if(o.length!==i.length)return!1;for(var f=0;f<o.length;f++)if(!(n.length&&~n.indexOf(o[f])||a.call(t,o[f])&&r(e[o[f]],t[o[f]])))return!1;return!0}Object.defineProperty(t,"__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},u="function"==typeof Symbol&&"symbol"===o(Symbol.iterator)?function(e){return"undefined"==typeof e?"undefined":o(e)}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":"undefined"==typeof e?"undefined":o(e)},a=Object.prototype.hasOwnProperty;t["default"]=n},function(e,t){function r(e,t){for(var r=-1,n=e?e.length:0,o=Array(n);++r<n;)o[r]=t(e[r],r,e);return o}e.exports=r},function(e,t){function r(e){return e}e.exports=r},function(e,t,r){function n(e){return null!=e&&u(e.length)&&!o(e)}var o=r(40),u=r(175);e.exports=n},function(e,t,r){function n(e){return"symbol"==typeof e||o(e)&&i.call(e)==u}var o=r(25),u="[object Symbol]",a=Object.prototype,i=a.toString;e.exports=n},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r=arguments.length<=2||void 0===arguments[2]?"":arguments[2],n=[],u=null;return Object.keys(e).some(function(o){var a=e[o];return a&&a.$form?""===a.$form.model?Object.keys(a).some(function(e){var n=a[e];return"$form"!==e&&!!n.$form&&!!(0,s["default"])(t,n.$form.model)&&(u=r?[r,o,e].join("."):[o,e].join("."),!0)}):!!(0,s["default"])(t,a.$form.model)&&(u=r?[r,o].join("."):o,!0):((0,l["default"])(a)&&n.push(o),!1)}),u?u:(n.some(function(n){return u=o(e[n],t,r?[r,n].join("."):n),!!u}),u?u:null)}function u(e,t){var r=o(e,t);return r?(0,i["default"])(e,r):null}Object.defineProperty(t,"__esModule",{value:!0}),t.getFormStateKey=o,t["default"]=u;var a=r(2),i=n(a),f=r(3),l=n(f),c=r(104),s=n(c);r(49)},function(e,t){"use strict";function r(e,t){return"function"==typeof e&&t?e(t):e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=e;return(0,f["default"])(t,".")?t=t.slice(0,-1):(0,f["default"])(t,"[]")&&(t=t.slice(0,-2)),(0,a["default"])(t)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(70),a=n(u),i=r(39),f=n(i)},function(e,t,r){function n(e,t){for(var r=e.length;r--;)if(o(e[r][0],t))return r;return-1}var o=r(172);e.exports=n},function(e,t,r){function n(e,t){var r=e.__data__;return o(t)?r["string"==typeof t?"string":"hash"]:r.map}var o=r(155);e.exports=n},function(e,t,r){var n=r(62),o=n(Object,"create");e.exports=o},function(e,t,r){function n(e){if("string"==typeof e||o(e))return e;var t=e+"";return"0"==t&&1/e==-u?"-0":t}var o=r(16),u=1/0;e.exports=n},function(e,t){function r(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}e.exports=r},function(e,t){function r(e){return!!e&&"object"==typeof e}e.exports=r},function(e,t,r){var n=r(13),o=r(119),u=r(58),a=r(59),i=r(60),f=r(143),l=r(23),c=i(function(e,t){return null==e?{}:(t=n(u(t,1),l),a(e,o(f(e),t)))});e.exports=c},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(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 i(e){return e.displayName||e.name||"Component"}function f(e,t){try{return e.apply(t)}catch(r){return M.value=r,M}}function l(e,t,r){var n=arguments.length<=3||void 0===arguments[3]?{}:arguments[3],l=Boolean(e),d=e||T,v=void 0;v="function"==typeof t?t:t?(0,b["default"])(t):S;var y=r||E,m=n.pure,g=void 0===m||m,_=n.withRef,O=void 0!==_&&_,w=g&&y!==E,k=x++;return function(e){function t(e,t,r){var n=y(e,t,r);return n}var r="Connect("+i(e)+")",n=function(n){function i(e,t){o(this,i);var a=u(this,n.call(this,e,t));a.version=k,a.store=e.store||t.store,(0,j["default"])(a.store,'Could not find "store" in either the context or '+('props of "'+r+'". ')+"Either wrap the root component in a <Provider>, "+('or explicitly pass "store" as a prop to "'+r+'".'));var f=a.store.getState();return a.state={storeState:f},a.clearCache(),a}return a(i,n),i.prototype.shouldComponentUpdate=function(){return!g||this.haveOwnPropsChanged||this.hasStoreStateChanged},i.prototype.computeStateProps=function(e,t){if(!this.finalMapStateToProps)return this.configureFinalMapState(e,t);var r=e.getState(),n=this.doStatePropsDependOnOwnProps?this.finalMapStateToProps(r,t):this.finalMapStateToProps(r);return n},i.prototype.configureFinalMapState=function(e,t){var r=d(e.getState(),t),n="function"==typeof r;return this.finalMapStateToProps=n?r:d,this.doStatePropsDependOnOwnProps=1!==this.finalMapStateToProps.length,n?this.computeStateProps(e,t):r},i.prototype.computeDispatchProps=function(e,t){if(!this.finalMapDispatchToProps)return this.configureFinalMapDispatch(e,t);var r=e.dispatch,n=this.doDispatchPropsDependOnOwnProps?this.finalMapDispatchToProps(r,t):this.finalMapDispatchToProps(r);return n},i.prototype.configureFinalMapDispatch=function(e,t){var r=v(e.dispatch,t),n="function"==typeof r;return this.finalMapDispatchToProps=n?r:v,this.doDispatchPropsDependOnOwnProps=1!==this.finalMapDispatchToProps.length,n?this.computeDispatchProps(e,t):r},i.prototype.updateStatePropsIfNeeded=function(){var e=this.computeStateProps(this.store,this.props);return!(this.stateProps&&(0,h["default"])(e,this.stateProps)||(this.stateProps=e,0))},i.prototype.updateDispatchPropsIfNeeded=function(){var e=this.computeDispatchProps(this.store,this.props);return!(this.dispatchProps&&(0,h["default"])(e,this.dispatchProps)||(this.dispatchProps=e,0))},i.prototype.updateMergedPropsIfNeeded=function(){var e=t(this.stateProps,this.dispatchProps,this.props);return!(this.mergedProps&&w&&(0,h["default"])(e,this.mergedProps)||(this.mergedProps=e,0))},i.prototype.isSubscribed=function(){return"function"==typeof this.unsubscribe},i.prototype.trySubscribe=function(){l&&!this.unsubscribe&&(this.unsubscribe=this.store.subscribe(this.handleChange.bind(this)),this.handleChange())},i.prototype.tryUnsubscribe=function(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null)},i.prototype.componentDidMount=function(){this.trySubscribe()},i.prototype.componentWillReceiveProps=function(e){g&&(0,h["default"])(e,this.props)||(this.haveOwnPropsChanged=!0)},i.prototype.componentWillUnmount=function(){this.tryUnsubscribe(),this.clearCache()},i.prototype.clearCache=function(){this.dispatchProps=null,this.stateProps=null,this.mergedProps=null,this.haveOwnPropsChanged=!0,this.hasStoreStateChanged=!0,this.haveStatePropsBeenPrecalculated=!1,this.statePropsPrecalculationError=null,this.renderedElement=null,this.finalMapDispatchToProps=null,this.finalMapStateToProps=null},i.prototype.handleChange=function(){if(this.unsubscribe){var e=this.store.getState(),t=this.state.storeState;if(!g||t!==e){if(g&&!this.doStatePropsDependOnOwnProps){var r=f(this.updateStatePropsIfNeeded,this);if(!r)return;r===M&&(this.statePropsPrecalculationError=M.value),this.haveStatePropsBeenPrecalculated=!0}this.hasStoreStateChanged=!0,this.setState({storeState:e})}}},i.prototype.getWrappedInstance=function(){return(0,j["default"])(O,"To access the wrapped instance, you need to specify { withRef: true } as the fourth argument of the connect() call."),this.refs.wrappedInstance},i.prototype.render=function(){var t=this.haveOwnPropsChanged,r=this.hasStoreStateChanged,n=this.haveStatePropsBeenPrecalculated,o=this.statePropsPrecalculationError,u=this.renderedElement;if(this.haveOwnPropsChanged=!1,this.hasStoreStateChanged=!1,this.haveStatePropsBeenPrecalculated=!1,this.statePropsPrecalculationError=null,o)throw o;var a=!0,i=!0;g&&u&&(a=r||t&&this.doStatePropsDependOnOwnProps,i=t&&this.doDispatchPropsDependOnOwnProps);var f=!1,l=!1;n?f=!0:a&&(f=this.updateStatePropsIfNeeded()),i&&(l=this.updateDispatchPropsIfNeeded());var d=!0;return d=!!(f||l||t)&&this.updateMergedPropsIfNeeded(),!d&&u?u:(O?this.renderedElement=(0,s.createElement)(e,c({},this.mergedProps,{ref:"wrappedInstance"})):this.renderedElement=(0,s.createElement)(e,this.mergedProps),this.renderedElement)},i}(s.Component);return n.displayName=r,n.WrappedComponent=e,n.contextTypes={store:p["default"]},n.propTypes={store:p["default"]},(0,P["default"])(n,e)}}var c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e};t.__esModule=!0,t["default"]=l;var s=r(8),d=r(185),p=n(d),v=r(184),h=n(v),y=r(187),b=n(y),m=r(186),g=(n(m),r(3)),_=(n(g),r(108)),P=n(_),O=r(109),j=n(O),T=function(e){return{}},S=function(e){return{dispatch:e}},E=function(e,t,r){return c({},r,e,t)},M={value:null},x=0},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){return"string"==typeof e||"number"==typeof e?""+e:""}function u(e){return(0,i["default"])(e.model)?!!e.modelValue&&e.modelValue.some(function(t){return t===e.value}):!!e.modelValue}Object.defineProperty(t,"__esModule",{value:!0});var a=r(51),i=n(a),f=r(9),l=n(f),c=r(10),s=n(c),d={value:function(e){return e.defaultValue||e.hasOwnProperty("value")?e.value:o(e.viewValue)},name:function(e){return e.name||e.model}},p={"default":d,checkbox:{name:function(e){return e.name||e.model},checked:function(e){return e.defaultChecked?e.checked:u(e)},changeAction:function(e){return function(t){var r=e.modelValue,n=e.value;if((0,i["default"])(t)){var o=r||[],u=(o||[]).filter(function(e){return e!==n}),a=u.length===o.length?l["default"].push(o,n):u;return s["default"].change(t,a)}return s["default"].change(t,!r)}}},radio:{name:function(e){return e.name||e.model},checked:function(e){return e.defaultChecked?e.checked:e.modelValue===e.value},value:function(e){return e.value}},select:{name:function(e){return e.name||e.model},value:function(e){return e.modelValue}},text:d,textarea:d,file:{name:function(e){return e.name||e.model}},reset:{onClick:function(e){return function(t){t.preventDefault(),e.dispatch(s["default"].reset(e.model))}}},label:{htmlFor:function(e){return e.htmlFor||e.model}}};t["default"]=p},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){return function(){var r=arguments.length<=0||void 0===arguments[0]?t:arguments[0],n=arguments[1];return n.type===a["default"].BATCH?n.actions.reduce(e,r):e(r,n)}}Object.defineProperty(t,"__esModule",{value:!0});var u=r(1),a=n(u);t["default"]=o},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return l["default"].setIn(e,t,r)}function u(){var e=arguments.length<=0||void 0===arguments[0]?i["default"]:arguments[0],t=arguments.length<=1||void 0===arguments[1]?o:arguments[1],r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2];return function(n){var o=arguments.length<=1||void 0===arguments[1]?r:arguments[1],u=(0,p["default"])(n),a=function(){var r=arguments.length<=0||void 0===arguments[0]?o:arguments[0],n=arguments[1];if(!n.model)return r;var a=(0,p["default"])(n.model);if(!(0,s["default"])(a.slice(0,u.length),u))return r;var i=a.slice(u.length);switch(n.type){case h["default"].CHANGE:case h["default"].LOAD:return i.length?e(r,i)===n.value?r:t(r,i,n.value):n.value;case h["default"].RESET:return i.length?e(r,i)===e(o,i)?r:t(r,i,e(o,i)):o;default:return r}};return(0,b["default"])(a,o)}}Object.defineProperty(t,"__esModule",{value:!0}),t.createModeler=void 0;var a=r(2),i=n(a),f=r(9),l=n(f),c=r(47),s=n(c),d=r(19),p=n(d),v=r(1),h=n(v),y=r(29),b=n(y),m=u();t.createModeler=u,t["default"]=m},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r=(0,s["default"])(e,t);if(!t.length)return r;var n=(0,f["default"])(r.$form.model),o=(0,f["default"])(t).slice(n.length),u=(0,a["default"])(r,o,l.initialFieldState);return u&&"$form"in u?u.$form:u?u:l.initialFieldState}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(2),a=n(u),i=r(19),f=n(i),l=r(7),c=r(17),s=n(c)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r=(0,a["default"])(t);return"function"==typeof e?e(r):(0,f["default"])(e,function(e){return o(e,r)})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(33),a=n(u),i=r(4),f=n(i)},function(e,t){"use strict";function r(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)}function n(e){return!!(e&&e.stopPropagation&&e.preventDefault)}function o(e){var t=e.target;if(!t){if(!e.nativeEvent)return;return e.nativeEvent.text}return"file"===t.type?[].concat(r(t.files))||t.dataTransfer&&[].concat(r(t.dataTransfer.files)):t.multiple?[].concat(r(t.selectedOptions)).map(function(e){return e.value}):t.value}function u(e){return n(e)?o(e):e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=u},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){return Array.isArray(e)?e:Array.from(e)}function u(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];return function(t){var n=e.split(/\[\]\.?/),u=o(n),a=u[0],i=u.slice(1),l=a,s=(0,c["default"])(t,l);return r.forEach(function(e,t){var r=i[t],n=(0,d["default"])(e),o=r?(0,f["default"])(s,n)+"."+r:""+(0,f["default"])(s,n);s=(0,c["default"])(s,o),l+="."+o}),l}}function a(e){return function(t){for(var r=arguments.length,n=Array(r>1?r-1:0),o=1;o<r;o++)n[o-1]=arguments[o];return"function"==typeof t?function(r,o){var u=t(o());r(e.apply(void 0,[u].concat(n)))}:e.apply(void 0,[t].concat(n))}}Object.defineProperty(t,"__esModule",{value:!0}),t.trackable=t.track=void 0;var i=r(97),f=n(i),l=r(2),c=n(l),s=r(52),d=n(s);t.track=u,t.trackable=a},function(e,t){function r(e,t){for(var r=-1,n=t.length,o=e.length;++r<n;)e[o+r]=t[r];return e}e.exports=r},function(e,t,r){var n=r(123),o=r(140),u=o(n);e.exports=u},function(e,t){function r(e,t){return function(r){return e(t(r))}}e.exports=r},function(e,t,r){var n=r(142),o="object"==typeof self&&self&&self.Object===Object&&self,u=n||o||Function("return this")();e.exports=u},function(e,t,r){function n(e,t,r){e=i(e),t=u(t);var n=e.length;r=void 0===r?n:o(a(r),0,n);var f=r;return r-=t.length,r>=0&&e.slice(r,f)==t}var o=r(118),u=r(61),a=r(182),i=r(71);e.exports=n},function(e,t,r){function n(e){var t=o(e)?f.call(e):"";return t==u||t==a}var o=r(24),u="[object Function]",a="[object GeneratorFunction]",i=Object.prototype,f=i.toString;e.exports=n},function(e,r){e.exports=t},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r=t.filter(function(e){return!!e});return r.length?r.length&&r.every(s["default"])?1===r.length?r[0]:{type:i["default"].BATCH,model:e,actions:r}:function(t){var n=(0,l["default"])(r,function(e){return"function"!=typeof e}),o=u(n,2),a=o[0],f=o[1];a.length>1?t({type:i["default"].BATCH,model:e,actions:a}):1===a.length&&t(a[0]),f.forEach(t)}:d}Object.defineProperty(t,"__esModule",{value:!0});var u=function(){function e(e,t){var r=[],n=!0,o=!1,u=void 0;try{for(var a,i=e[Symbol.iterator]();!(n=(a=i.next()).done)&&(r.push(a.value),!t||r.length!==t);n=!0);}catch(f){o=!0,u=f}finally{try{!n&&i["return"]&&i["return"]()}finally{if(o)throw u}}return r}return function(t,r){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,r);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),a=r(1),i=n(a),f=r(103),l=n(f),c=r(3),s=n(c),d={type:i["default"].NULL};t["default"]={batch:o}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}Object.defineProperty(t,"__esModule",{value:!0});var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},a=r(2),i=n(a),f=r(4),l=n(f),c=r(1),s=n(c),d=r(42),p=n(d),v=r(32),h=n(v),y=r(102),b=n(y),m=r(101),g=n(m),_=r(34),P=r(17),O=n(P),j=r(11),T=n(j),S=(0,_.trackable)(function(e){return{type:s["default"].FOCUS,model:e}}),E=(0,_.trackable)(function(e){return{type:s["default"].BLUR,model:e}}),M=(0,_.trackable)(function(e){return{type:s["default"].SET_PRISTINE,model:e}}),x=(0,_.trackable)(function(e){return{type:s["default"].SET_DIRTY,model:e}}),w=(0,_.trackable)(function(e){return{type:s["default"].SET_INITIAL,model:e}}),k=(0,_.trackable)(function(e){var t=arguments.length<=1||void 0===arguments[1]||arguments[1];return{type:s["default"].SET_PENDING,model:e,pending:t}}),V=(0,_.trackable)(function(e){var t=arguments.length<=1||void 0===arguments[1]||arguments[1];return{type:s["default"].SET_VALIDATING,model:e,validating:t}}),A=(0,_.trackable)(function(e,t){var r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2];return o({type:r.errors?s["default"].SET_ERRORS:s["default"].SET_VALIDITY,model:e},r.errors?"errors":"validity",t)}),C=(0,_.trackable)(function(e,t){var r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2];return{type:s["default"].SET_FIELDS_VALIDITY,model:e,fieldsValidity:t,options:r}}),I=(0,_.trackable)(function(e,t){var r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2];return A(e,t,u({},r,{errors:!0}))}),F=(0,_.trackable)(function(e,t,r){return C(e,t,u({},r,{errors:!0}))}),D=(0,_.trackable)(function(e){return{type:s["default"].RESET_VALIDITY,model:e}}),R=D,N=(0,_.trackable)(function(e){return{type:s["default"].SET_TOUCHED,model:e}}),$=(0,_.trackable)(function(e){return{type:s["default"].SET_UNTOUCHED,model:e}}),U=(0,_.trackable)(function(e,t){return function(r,n){var o=(0,i["default"])(n(),e);r(V(e,!0));var u=function(t){r(A(e,t))},a=t(o,u);"undefined"!=typeof a&&u(a)}}),L=(0,_.trackable)(function(e){var t=arguments.length<=1||void 0===arguments[1]||arguments[1];return{type:s["default"].SET_SUBMITTED,model:e,submitted:t}}),H=(0,_.trackable)(function(e){var t=arguments.length<=1||void 0===arguments[1]||arguments[1];return{type:s["default"].SET_SUBMIT_FAILED,model:e,submitFailed:t}}),B=(0,_.trackable)(function(e,t){var r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2];return function(n){n(k(e,!0));var o=r.fields?F:I;return t.then(function(t){n(p["default"].batch(e,[L(e,!0),A(e,t)]))})["catch"](function(t){n(p["default"].batch(e,[H(e),o(e,t)]))}),t}}),G=(0,_.trackable)(function(e,t){var r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2];return B(e,t,u({},r,{fields:!0}))}),K=(0,_.trackable)(function(e,t){return function(r,n){var o=(0,i["default"])(n(),e),u=(0,h["default"])(t,o);r(A(e,u))}}),q=(0,_.trackable)(function(e,t){return function(r,n){var o=(0,i["default"])(n(),e),u=(0,h["default"])(t,o);r(A(e,u,{errors:!0}))}}),Y=(0,_.trackable)(function(e,t){var r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2];return function(n,o){var u=(0,i["default"])(o(),e),a=(0,l["default"])(t,function(e,t){var r=t?(0,i["default"])(u,t):u,n=(0,h["default"])(e,r);return n}),f=r.onValid,c=r.onInvalid;if(f||c){var s=(0,O["default"])(o(),e),d=!(s&&!a.hasOwnProperty(""))||(0,T["default"])(s),p=r.errors?!(0,g["default"])(a):(0,b["default"])(a);f&&d&&p?f():c&&c()}var v=r.errors?F:C;n(v(e,a))}}),W=(0,_.trackable)(function(e,t){var r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2];return Y(e,t,u({},r,{errors:!0}))});t["default"]={blur:E,focus:S,submit:B,submitFields:G,setDirty:x,setErrors:I,setInitial:w,setPending:k,setValidating:V,setPristine:M,setSubmitted:L,setSubmitFailed:H,setTouched:N,setUntouched:$,setValidity:A,setFieldsValidity:C,setFieldsErrors:F,resetValidity:D,resetErrors:R,validate:K,validateErrors:q,validateFields:Y,validateFieldsErrors:W,asyncSetValidity:U}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function u(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 i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function f(e,t){var r=t.model,n=t.mapProps,o=t.getter,u=void 0===o?O["default"]:o,a=t.controlProps,i=void 0===a?(0,A["default"])(t,Object.keys(te)):a;if(!n)return t;var f=(0,G["default"])(r,e),l=(0,H["default"])(e,f);return{model:r,modelValue:u(e,f),fieldValue:l,controlProps:i}}function l(e){return~["radio","checkbox"].indexOf(e.type)}Object.defineProperty(t,"__esModule",{value:!0});var c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),d=r(8),p=r(188),v=r(27),h=n(v),y=r(41),b=r(14),m=n(b),g=r(12),_=n(g),P=r(2),O=n(P),j=r(54),T=n(j),S=r(4),E=n(S),M=r(3),x=n(M),w=r(9),k=n(w),V=r(26),A=n(V),C=r(72),I=n(C),F=r(33),D=n(F),R=r(32),N=n(R),$=r(50),U=n($),L=r(31),H=n(L),B=r(18),G=n(B),K=r(105),q=n(K),Y=r(10),W=n(Y),z=r(11),J=n(z),Q=r(28),X=n(Q),Z=r(78),ee=n(Z),te={model:d.PropTypes.oneOfType([d.PropTypes.func,d.PropTypes.string]),modelValue:d.PropTypes.any,viewValue:d.PropTypes.any,control:d.PropTypes.any,onLoad:d.PropTypes.func,onSubmit:d.PropTypes.func,fieldValue:d.PropTypes.object,mapProps:d.PropTypes.oneOfType([d.PropTypes.func,d.PropTypes.object]),changeAction:d.PropTypes.func,updateOn:d.PropTypes.string,validateOn:d.PropTypes.string,validators:d.PropTypes.oneOfType([d.PropTypes.func,d.PropTypes.object]),asyncValidateOn:d.PropTypes.string,asyncValidators:d.PropTypes.oneOfType([d.PropTypes.func,d.PropTypes.object]),errors:d.PropTypes.oneOfType([d.PropTypes.func,d.PropTypes.object]),controlProps:d.PropTypes.object,component:d.PropTypes.any,dispatch:d.PropTypes.func,parser:d.PropTypes.func,formatter:d.PropTypes.func,getter:d.PropTypes.func, ignore:d.PropTypes.arrayOf(d.PropTypes.string),dynamic:d.PropTypes.bool},re=function(e){function t(e){u(this,t);var r=a(this,Object.getPrototypeOf(t).call(this,e));return r.getChangeAction=r.getChangeAction.bind(r),r.getValidateAction=r.getValidateAction.bind(r),r.handleKeyPress=r.handleKeyPress.bind(r),r.createEventHandler=r.createEventHandler.bind(r),r.handleFocus=r.createEventHandler("focus").bind(r),r.handleBlur=r.createEventHandler("blur").bind(r),r.handleUpdate=r.createEventHandler("change").bind(r),r.handleChange=r.handleChange.bind(r),r.handleLoad=r.handleLoad.bind(r),r.getMappedProps=r.getMappedProps.bind(r),r.attachNode=r.attachNode.bind(r),r.state={viewValue:e.modelValue,mappedProps:{}},r}return i(t,e),s(t,[{key:"componentWillMount",value:function(){var e=this.props,t=this.props.mapProps;this.setState({mappedProps:this.getMappedProps(e,t)})}},{key:"componentDidMount",value:function(){this.attachNode(),this.handleLoad()}},{key:"componentWillReceiveProps",value:function(e){var t=e.mapProps,r=e.modelValue;this.setState({viewValue:r,mappedProps:this.getMappedProps(e,t)})}},{key:"shouldComponentUpdate",value:function(e,t){return(0,I["default"])(this,e,t)}},{key:"componentDidUpdate",value:function(e,t){var r=this.props,n=r.modelValue,o=r.fieldValue,u=r.validateOn,a=r.validators,i=r.errors,f=this.state.viewValue;(a||i)&&o&&!o.validated&&n!==e.modelValue&&"change"===u&&this.validate(),o.focus?document&&document.activeElement!==this.node&&this.node.focus&&this.node.focus():document&&document.activeElement===this.node&&this.node.blur&&this.node.blur(),t.viewValue!==f&&this.updateMappedProps()}},{key:"componentWillUnmount",value:function(){var e=this.props,t=e.model,r=e.fieldValue,n=e.dispatch;r&&((0,J["default"])(r)||n(W["default"].resetValidity(t)))}},{key:"getMappedProps",value:function(e,t){var r=this.state.viewValue,n=c({},e,e.controlProps,{onFocus:this.handleFocus,onBlur:this.handleBlur,onChange:this.handleChange,onKeyPress:this.handleKeyPress,viewValue:r});return(0,x["default"])(t)?k["default"].merge(n,(0,E["default"])(t,function(e,t){return"function"==typeof e&&"component"!==t?e(n):e})):t(n)}},{key:"getChangeAction",value:function(e){var t=this.props,r=t.model,n=t.controlProps,o=this.state.mappedProps.changeAction,u=void 0===o?W["default"].change:o,a=l(n)?n.value:e;return u(r,(0,D["default"])(a))}},{key:"getValidateAction",value:function(e){var t=this.props,r=t.validators,n=t.errors,o=t.model,u=t.fieldValue,a=this.getNodeErrors();if(r||n){var i=(0,N["default"])(r,e),f=(0,T["default"])((0,N["default"])(n,e),a),l=r?(0,T["default"])((0,U["default"])(i),f):f;if(!u||!(0,_["default"])(l,u.errors))return W["default"].setErrors(o,l)}else if(a)return W["default"].setErrors(o,a);return!1}},{key:"getAsyncValidateAction",value:function(e){var t=this.props,r=t.asyncValidators,n=t.fieldValue,u=t.model;return!!r&&function(t){return(0,E["default"])(r,function(r,a){return t(W["default"].asyncSetValidity(u,function(t,u){var i=function(e){var t=k["default"].merge(n.validity,o({},a,e));u(t)};r((0,D["default"])(e),i)}))}),e}}},{key:"getNodeErrors",value:function(){var e=this.node;if(!e||!e.willValidate)return null;var t={};return ee["default"].forEach(function(r){t[r]=e.validity[r]}),t}},{key:"updateMappedProps",value:function(){var e=this.props.mapProps;this.setState({mappedProps:this.getMappedProps(this.props,e)})}},{key:"handleChange",value:function(e){this.setState({viewValue:(0,D["default"])(e)}),this.handleUpdate(e)}},{key:"handleKeyPress",value:function(e){"Enter"===e.key&&this.handleSubmit(e)}},{key:"handleLoad",value:function(){var e=this.props,t=e.model,r=e.modelValue,n=e.fieldValue,o=e.controlProps,u=void 0===o?{}:o,a=e.onLoad,i=e.dispatch,f=[],l=void 0;u.hasOwnProperty("defaultValue")?l=u.defaultValue:u.hasOwnProperty("defaultChecked")&&(l=u.defaultChecked),"undefined"!=typeof l?(f.push(this.getValidateAction(l)),f.push(W["default"].change(t,l))):f.push(this.getValidateAction(r)),i(W["default"].batch(t,f)),a&&a(r,n,this.node)}},{key:"handleSubmit",value:function(e){var t=this.props.dispatch;t(this.getChangeAction(e))}},{key:"createEventHandler",value:function(e){var t=this,r=this.props,n=r.dispatch,o=r.model,u=r.updateOn,a=r.validateOn,i=r.asyncValidateOn,f=r.controlProps,c=void 0===f?{}:f,s=r.parser,d=r.ignore,p={focus:W["default"].focus,blur:W["default"].blur}[e],v={focus:c.onFocus,blur:c.onBlur,change:c.onChange}[e],h=function(r){var f=p?[p(o)]:[];a===e&&f.push(t.getValidateAction(r)),i===e&&f.push(t.getAsyncValidateAction(r)),u===e&&f.push(t.getChangeAction(r));var l=f.filter(function(e){return!!e});return l.length&&n(W["default"].batch(o,l)),r};return function(t){return~d.indexOf(e)?v?v(t):t:l(c)?(0,y.compose)(h,(0,q["default"])(v||m["default"]))(t):(0,y.compose)(h,s,D["default"],(0,q["default"])(v||m["default"]))(t)}}},{key:"attachNode",value:function(){var e=(0,p.findDOMNode)(this);e&&(this.node=e)}},{key:"validate",value:function(){var e=this.props,t=e.model,r=e.modelValue,n=e.fieldValue,o=e.validators,u=e.errors,a=e.dispatch;if(!o&&!u)return r;var i=(0,N["default"])(o,r),f=(0,N["default"])(u,r),l=o?(0,T["default"])((0,U["default"])(i),f):f;return(0,_["default"])(l,n.errors)||a(W["default"].setErrors(t,l)),r}},{key:"render",value:function(){var e=this.props,t=e.controlProps,r=void 0===t?{}:t,n=e.component,o=e.control,u=(0,A["default"])(this.state.mappedProps,Object.keys(te));return o?(0,d.cloneElement)(o,c({},u,{onKeyPress:this.handleKeyPress})):(0,d.createElement)(n,c({},r,u,{onKeyPress:this.handleKeyPress}),r.children)}}]),t}(d.Component);re.propTypes=te,re.defaultProps={changeAction:W["default"].change,updateOn:"change",parser:m["default"],formatter:m["default"],controlProps:{},getter:O["default"],ignore:[],dynamic:!1};var ne=(0,h["default"])(f)(re);ne.text=function(e){function t(){return u(this,t),a(this,Object.getPrototypeOf(t).apply(this,arguments))}return i(t,e),t}(ne),ne.text.defaultProps=c({},ne.defaultProps,{component:"input",mapProps:X["default"].text}),ne.radio=function(e){function t(){return u(this,t),a(this,Object.getPrototypeOf(t).apply(this,arguments))}return i(t,e),t}(ne),ne.radio.defaultProps=c({},ne.defaultProps,{component:"input",type:"radio",mapProps:X["default"].radio}),ne.checkbox=function(e){function t(){return u(this,t),a(this,Object.getPrototypeOf(t).apply(this,arguments))}return i(t,e),t}(ne),ne.checkbox.defaultProps=c({},ne.defaultProps,{component:"input",type:"checkbox",mapProps:X["default"].checkbox}),ne.file=function(e){function t(){return u(this,t),a(this,Object.getPrototypeOf(t).apply(this,arguments))}return i(t,e),t}(ne),ne.file.defaultProps=c({},ne.defaultProps,{component:"input",type:"file",mapProps:X["default"].file}),ne.select=function(e){function t(){return u(this,t),a(this,Object.getPrototypeOf(t).apply(this,arguments))}return i(t,e),t}(ne),ne.select.defaultProps=c({},ne.defaultProps,{component:"select",mapProps:X["default"].select}),t["default"]=ne},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(){var e=arguments.length<=0||void 0===arguments[0]?a["default"]:arguments[0];return function(t,r){var n=void 0;try{n=t(void 0,f["default"])}catch(o){n=null}var u=e(r,n);return function(){var e=arguments.length<=0||void 0===arguments[0]?n:arguments[0],r=arguments[1],o=u(e,r);return t(o,r)}}}Object.defineProperty(t,"__esModule",{value:!0}),t.createModelReducerEnhancer=void 0;var u=r(30),a=n(u),i=r(77),f=n(i),l=o(a["default"]);t.createModelReducerEnhancer=o,t["default"]=l},function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t["default"]=e,t}function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.track=t.getField=t.utils=t.form=t.batched=t.modeled=t.createFieldClass=t.Errors=t.Form=t.Control=t.Field=t.controls=t.actionTypes=t.actions=t.initialFieldState=t.combineForms=t.modelReducer=t.formReducer=void 0;var u=r(10),a=o(u),i=r(1),f=o(i),l=r(75),c=o(l),s=r(44),d=o(s),p=r(76),v=o(p),h=r(74),y=o(h),b=r(28),m=o(b),g=r(45),_=o(g),P=r(29),O=o(P),j=r(7),T=o(j),S=r(95),E=o(S),M=r(30),x=o(M),w=r(34),k=r(49),V=n(k),A=r(79),C=o(A);t.formReducer=T["default"],t.modelReducer=x["default"],t.combineForms=E["default"],t.initialFieldState=j.initialFieldState,t.actions=a["default"],t.actionTypes=f["default"],t.controls=m["default"],t.Field=c["default"],t.Control=d["default"],t.Form=v["default"],t.Errors=y["default"],t.createFieldClass=l.createFieldClass,t.modeled=_["default"],t.batched=O["default"],t.form=C["default"],t.utils=V,t.getField=j.getField,t.track=w.track},function(e,t){"use strict";function r(e,t){return e&&t&&e.length===t.length&&e.every(function(e,r){return e===t[r]})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r=e.children,n=t.children;if(i["default"].Children.count(r)!==i["default"].Children.count(n)||!i["default"].Children.count(r)||!i["default"].Children.count(n))return!0;var o=i["default"].Children.toArray(r),a=i["default"].Children.toArray(n);return[].concat(o).some(function(e,t){var r=a[t];return e.props&&r.props?u(e,r.props,r.state):!(0,s["default"])(e,r)})}function u(e,t,r){return e.props.children?(0,l["default"])(e,t,r)&&o(e.props,t):(0,l["default"])(e,t,r)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=u;var a=r(8),i=n(a),f=r(72),l=n(f),c=r(12),s=n(c)},function(e,t){},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){return(0,a["default"])(e)?(0,f["default"])(e,o):!e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(3),a=n(u),i=r(4),f=n(i)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){return(0,a["default"])(e,"[]")}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(39),a=n(u)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){return function(t){return t===e||Object.keys(e).every(function(r){return e[r]===t[r]})}}function u(e){return function(t){return t&&!!t[e]}}function a(e){return"function"==typeof e?e:null===e?l["default"]:"object"===("undefined"==typeof e?"undefined":i(e))?o(e):u(e)}Object.defineProperty(t,"__esModule",{value:!0});var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e};t["default"]=a;var f=r(14),l=n(f)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r=Array.isArray(e)?a["default"]:f["default"];return r(e,t)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(13),a=n(u),i=r(131),f=n(i)},function(e,t){"use strict";function r(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function n(e){return e&&"object"===("undefined"==typeof e?"undefined":u(e))&&!Array.isArray(e)&&null!==e}function o(e,t){return n(e)&&n(t)&&Object.keys(t).forEach(function(u){n(t[u])?(e[u]||Object.assign(e,r({},u,{})),o(e[u],t[u])):Object.assign(e,r({},u,t[u]))}),e}Object.defineProperty(t,"__esModule",{value:!0});var u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e};t["default"]=o},function(e,t,r){function n(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}var o=r(162),u=r(163),a=r(164),i=r(165),f=r(166);n.prototype.clear=o,n.prototype["delete"]=u,n.prototype.get=a,n.prototype.has=i,n.prototype.set=f,e.exports=n},function(e,t,r){var n=r(38),o=n.Symbol;e.exports=o},function(e,t,r){function n(e,t){var r=a(e)||f(e)||u(e)?o(e.length,String):[],n=r.length,l=!!n;for(var s in e)!t&&!c.call(e,s)||l&&("length"==s||i(s,n))||r.push(s);return r}var o=r(134),u=r(68),a=r(6),i=r(153),f=r(176),l=Object.prototype,c=l.hasOwnProperty;e.exports=n},function(e,t,r){function n(e,t,r,a,i){var f=-1,l=e.length;for(r||(r=u),i||(i=[]);++f<l;){var c=e[f];t>0&&r(c)?t>1?n(c,t-1,r,a,i):o(i,c):a||(i[i.length]=c)}return i}var o=r(35),u=r(152);e.exports=n},function(e,t,r){function n(e,t){return e=Object(e),o(e,t,function(t,r){return r in e})}var o=r(132);e.exports=n},function(e,t,r){function n(e,t){return t=u(void 0===t?e.length-1:t,0),function(){for(var r=arguments,n=-1,a=u(r.length-t,0),i=Array(a);++n<a;)i[n]=r[t+n];n=-1;for(var f=Array(t+1);++n<t;)f[n]=r[n];return f[t]=i,o(e,this,f)}}var o=r(114),u=Math.max;e.exports=n},function(e,t,r){function n(e){if("string"==typeof e)return e;if(u(e))return f?f.call(e):"";var t=e+"";return"0"==t&&1/e==-a?"-0":t}var o=r(56),u=r(16),a=1/0,i=o?o.prototype:void 0,f=i?i.toString:void 0;e.exports=n},function(e,t,r){function n(e,t){var r=u(e,t);return o(r)?r:void 0}var o=r(128),u=r(146);e.exports=n},function(e,t,r){var n=r(37),o=n(Object.getPrototypeOf,Object);e.exports=o},function(e,t){function r(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(r){}return t}e.exports=r},function(e,t){function r(e){var t=e&&e.constructor,r="function"==typeof t&&t.prototype||n;return e===r}var n=Object.prototype;e.exports=r},function(e,t,r){var n=r(179),o=r(71),u=/^\./,a=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,i=/\\(\\)?/g,f=n(function(e){e=o(e);var t=[];return u.test(e)&&t.push(""),e.replace(a,function(e,r,n,o){t.push(n?o.replace(i,"$1"):r||e)}),t});e.exports=f},function(e,t){function r(e){for(var t=-1,r=e?e.length:0,n=0,o=[];++t<r;){var u=e[t];u&&(o[n++]=u)}return o}e.exports=r},function(e,t,r){function n(e){return o(e)&&i.call(e,"callee")&&(!l.call(e,"callee")||f.call(e)==u)}var o=r(174),u="[object Arguments]",a=Object.prototype,i=a.hasOwnProperty,f=a.toString,l=a.propertyIsEnumerable;e.exports=n},function(e,t){function r(){return[]}e.exports=r},function(e,t,r){function n(e){return a(e)?o(e,l):i(e)?[e]:u(f(e))}var o=r(13),u=r(138),a=r(6),i=r(16),f=r(66),l=r(23);e.exports=n},function(e,t,r){function n(e){return null==e?"":o(e)}var o=r(61);e.exports=n},function(e,t,r){"use strict";function n(e,t,r){return!o(e.props,t)||!o(e.state,r)}var o=r(107);e.exports=n},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)}function u(){var e=arguments.length<=0||void 0===arguments[0]?O:arguments[0],t=function(t,r){var n=arguments.length<=2||void 0===arguments[2]?{}:arguments[2],o=a({silent:!1,multi:(0,y["default"])(t)},n);return a({type:m["default"].CHANGE,model:t,value:e.getValue(r)},o)},r=function(t,r){var n=arguments.length<=2||void 0===arguments[2]?function(e){return e===r}:arguments[2];return function(u,a){var i=e.get(a(),t,[]),f=i.filter(function(e){return!n(e)}),l=i.length===f.length?[].concat(o(i),[r]):f;u({type:m["default"].CHANGE,model:t,value:l})}},n=function(t){var r=arguments.length<=1||void 0===arguments[1]?null:arguments[1];return function(n,u){var a=e.get(u(),t),i=[].concat(o(a||[]),[r]);n({type:m["default"].CHANGE,model:t,value:i})}},u=function(t){return function(r,n){var o=!e.get(n(),t);r({type:m["default"].CHANGE,model:t,value:o})}},i=function(t){var r=arguments.length<=1||void 0===arguments[1]?c["default"]:arguments[1];return function(n,o){var u=e.get(o(),t),a=u.filter(r);n({type:m["default"].CHANGE,model:t,value:a})}},f=function(e){return{type:m["default"].RESET,model:e}},l=function(t){var r=arguments.length<=1||void 0===arguments[1]?c["default"]:arguments[1];return function(n,o){var u=e.get(o(),t,[]),a=u.map(r);n({type:m["default"].CHANGE,model:t,value:a})}},s=function(t,r){return function(n,o){var u=e.get(o(),t,[]);n({type:m["default"].CHANGE,model:t,value:e.splice(u,r,1),removeKeys:[r]})}},d=function(t,r,n){return function(o,u){var a=e.get(u(),t,[]);if(r>=a.length||n>=a.length)throw new Error("Error moving array item: invalid bounds "+r+", "+n);var i=a[r],f=e.splice(a,r,1),l=e.splice(f,n,0,i);o({type:m["default"].CHANGE,model:t,value:l})}},p=function(t,r){return function(n,o){var u=e.get(o(),t,{});n({type:m["default"].CHANGE,model:t,value:e.merge(u,r)})}},v=function(t){var r=arguments.length<=1||void 0===arguments[1]?[]:arguments[1];return function(n,o){var u=e.get(o(),t,{}),a="string"==typeof r?[r]:r,i=a.reduce(function(t,r){return e.remove(t,r)},u);n({type:m["default"].CHANGE,model:t,value:i,removeKeys:a})}},h=function(e,r){return t(e,r,{silent:!0})};return(0,_["default"])({change:t,filter:i,map:l,merge:p,push:n,remove:s,move:d,reset:f,toggle:u,xor:r,load:h,omit:v},P.trackable)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},i=r(2),f=n(i),l=r(14),c=n(l),s=r(9),d=n(s),p=r(33),v=n(p),h=r(51),y=n(h),b=r(1),m=n(b),g=r(4),_=n(g),P=r(34),O={get:f["default"],getValue:v["default"],splice:d["default"].splice,merge:d["default"].merge,remove:d["default"].dissoc};t["default"]=u()},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(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 i(e,t){var r=arguments.length<=2||void 0===arguments[2]||arguments[2];return"function"==typeof r?r(e,t):(0,T["default"])(r)||"object"===("undefined"==typeof r?"undefined":c(r))||"string"==typeof r?(0,O["default"])(r)(e):!!r}function f(e,t){var r=t.model,n=(0,I["default"])(r,e),o=(0,k["default"])(e,n).$form,u=(0,A["default"])(e,n);return{model:n,modelValue:(0,y["default"])(e,n),formValue:o,fieldValue:u}}Object.defineProperty(t,"__esModule",{value:!0});var l=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},s=r(8),d=n(s),p=r(27),v=n(p),h=r(2),y=n(h),b=r(53),m=n(b),g=r(67),_=n(g),P=r(52),O=n(P),j=r(6),T=n(j),S=r(3),E=n(S),M=r(26),x=n(M),w=r(17),k=n(w),V=r(31),A=n(V),C=r(18),I=n(C),F=r(11),D=n(F),R=function(e){function t(){return o(this,t),u(this,Object.getPrototypeOf(t).apply(this,arguments))}return a(t,e),l(t,[{key:"shouldComponentUpdate",value:function(e){var t=e.fieldValue,r=e.formValue;return t!==this.props.fieldValue||r!==this.props.formValue}},{key:"mapErrorMessages",value:function(e){var t=this,r=this.props.messages;if("string"==typeof e)return this.renderError(e,"error");if(!e)return null;var n=(0,_["default"])((0,m["default"])(e,function(e,n){var o=r[n];if(e){if(o)return t.renderError(o,n);if("string"==typeof e)return t.renderError(e,n);if((0,E["default"])(e))return t.mapErrorMessages(e)}return!1})).reduce(function(e,t){return e.concat(t)},[]);return n.length?n:null}},{key:"renderError",value:function(e,t){var r=this.props,n=r.component,o=r.model,u=r.modelValue,a=r.fieldValue,i=r.fieldValue.errors,f={key:t,model:o,modelValue:u,fieldValue:a},l="function"==typeof e?e(u,i[t]):e;if(!l)return null;var c="function"==typeof n?f:{key:t};return d["default"].createElement(n,c,l)}},{key:"render",value:function(){var e=this.props,r=e.fieldValue,n=e.formValue,o=e.show,u=e.wrapper,a="function"==typeof u?this.props:(0,x["default"])(this.props,Object.keys(t.propTypes));if(!i(r,n,o))return null;var f=(0,D["default"])(r)?null:this.mapErrorMessages(r.errors);return f?d["default"].createElement(u,a,f):null}}]),t}(s.Component);R.propTypes={modelValue:s.PropTypes.any,formValue:s.PropTypes.object,fieldValue:s.PropTypes.object,model:s.PropTypes.string.isRequired,messages:s.PropTypes.objectOf(s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.func,s.PropTypes.bool])),show:s.PropTypes.any,wrapper:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.func,s.PropTypes.element]),component:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.func,s.PropTypes.element]),dispatch:s.PropTypes.func},R.defaultProps={wrapper:"div",component:"span",messages:{},show:!0},t["default"]=(0,v["default"])(f)(R)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(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 i(e,t){var r=t.model,n=(0,D["default"])(r,e),o=(0,N["default"])(e,n);return{model:r,fieldValue:o}}function f(e,t,r){var n=r.controlPropsMap,o=Object.keys(n).filter(function(t){var r=n[t];return!(!(0,_["default"])(r)||!r.component)&&e.type===r.component});if(o.length)return o[0];try{var u=e.constructor.displayName||e.type.displayName||e.type.name||e.type;return"input"===u&&(u=n[e.props.type]?e.props.type:"text"),n[u]?u:null}catch(a){return}}function l(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],r={controlPropsMap:s({},k["default"],e)},n=function(e){function t(){return o(this,t),u(this,Object.getPrototypeOf(t).apply(this,arguments))}return a(t,e),c(t,[{key:"shouldComponentUpdate",value:function(e){var t=this.props.dynamic;return t?(0,A["default"])(this,e):(0,I["default"])(this,e)}},{key:"createControlComponent",value:function(e){var t=this.props;if(!e||!e.props||e instanceof x["default"])return e;var n=f(e,t,r),o=t.mapProps,u=void 0===o?r.controlPropsMap[n]:o,a=(0,O["default"])(t,Object.keys($));return u?p["default"].createElement(x["default"],s({},a,{control:e,controlProps:e.props,component:e.type,mapProps:u})):p["default"].cloneElement(e,null,this.mapChildrenToControl(e.props.children))}},{key:"mapChildrenToControl",value:function(e){var t=this;return p["default"].Children.count(e)>1?p["default"].Children.map(e,function(e){return t.createControlComponent(e)}):this.createControlComponent(e)}},{key:"render",value:function(){var e=this,t=this.props,r=t.component,n=t.children,o=t.fieldValue,u=(0,m["default"])(t,Object.keys($)),a="function"==typeof n?n(o):n;return p["default"].createElement(r,u,p["default"].Children.map(a,function(t){return e.createControlComponent(t)}))}}]),t}(d.Component);return n.propTypes=$,n.defaultProps=s({updateOn:"change",validateOn:"change",asyncValidateOn:"blur",parser:y["default"],changeAction:E["default"].change,dynamic:!1,component:"div"},t),(0,T["default"])(i)(n)}Object.defineProperty(t,"__esModule",{value:!0}),t.createFieldClass=t.controlPropsMap=void 0;var c=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},d=r(8),p=n(d),v=r(2),h=(n(v),r(14)),y=n(h),b=r(26),m=n(b),g=r(3),_=n(g),P=r(180),O=n(P),j=r(27),T=n(j),S=r(10),E=n(S),M=r(44),x=n(M),w=r(28),k=n(w),V=r(48),A=n(V),C=r(106),I=n(C),F=r(18),D=n(F),R=r(31),N=n(R),$={model:d.PropTypes.oneOfType([d.PropTypes.func,d.PropTypes.string]).isRequired,component:d.PropTypes.oneOfType([d.PropTypes.func,d.PropTypes.string]),parser:d.PropTypes.func,updateOn:d.PropTypes.oneOf(["change","blur","focus"]),changeAction:d.PropTypes.func,validators:d.PropTypes.oneOfType([d.PropTypes.func,d.PropTypes.object]),asyncValidators:d.PropTypes.object,validateOn:d.PropTypes.string,asyncValidateOn:d.PropTypes.string,errors:d.PropTypes.oneOfType([d.PropTypes.func,d.PropTypes.object]),mapProps:d.PropTypes.func,componentMap:d.PropTypes.object,dynamic:d.PropTypes.bool,dispatch:d.PropTypes.func,getter:d.PropTypes.func,fieldValue:d.PropTypes.object};t.controlPropsMap=k["default"],t.createFieldClass=l,t["default"]=l(k["default"])},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(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 i(e,t){var r=t.model,n=(0,R["default"])(r,e);return{modelValue:(0,b["default"])(e,n),formValue:(0,F["default"])(e,n)}}Object.defineProperty(t,"__esModule",{value:!0});var f=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},l=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),c=r(8),s=n(c),d=r(27),p=n(d),v=r(12),h=n(v),y=r(2),b=n(y),m=r(4),g=n(m),_=r(54),P=n(_),O=r(14),j=n(O),T=r(26),S=n(T),E=r(10),M=n(E),x=r(32),w=n(x),k=r(50),V=n(k),A=r(100),C=n(A),I=r(17),F=n(I),D=r(18),R=n(D),N=r(7),$=r(11),U=n($),L=r(48),H=n(L),B=function(e){function t(e){o(this,t);var r=u(this,Object.getPrototypeOf(t).call(this,e));return r.handleSubmit=r.handleSubmit.bind(r),r.handleReset=r.handleReset.bind(r),r.handleValidSubmit=r.handleValidSubmit.bind(r),r.handleInvalidSubmit=r.handleInvalidSubmit.bind(r),r.attachNode=r.attachNode.bind(r),r}return a(t,e),l(t,[{key:"componentDidMount",value:function(){"change"===this.props.validateOn&&this.validate(this.props,!0)}},{key:"componentWillReceiveProps",value:function(e){var t=this.props.validateOn;"change"===t&&this.validate(e)}},{key:"shouldComponentUpdate",value:function(e){return(0,H["default"])(this,e)}},{key:"attachNode",value:function(e){e&&(this._node=e,this._node.submit=this.handleSubmit)}},{key:"validate",value:function(e){var t=!(arguments.length<=1||void 0===arguments[1])&&arguments[1],r=this.props,n=r.validators,o=r.errors,u=r.model,a=r.dispatch,i=r.formValue,f=r.modelValue;if(i){if(!n&&!o&&f!==e.modelValue)return void((0,U["default"])(i)||a(M["default"].setValidity(u,!0)));var l=!1,c=(0,g["default"])(n,function(r,n){var o=n?(0,b["default"])(e.modelValue,n):e.modelValue,u=n?(0,b["default"])(f,n):f,a=(0,N.getField)(i,n).validity;if(!t&&o===u)return a;var c=(0,w["default"])(r,o);return(0,h["default"])(c,a)||(l=!0),c}),s=(0,g["default"])(o,function(r,n){var o=n?(0,b["default"])(e.modelValue,n):e.modelValue,u=n?(0,b["default"])(f,n):f,a=(0,N.getField)(i,n).errors;if(!t&&o===u)return(0,N.getField)(i,n).errors;var c=(0,w["default"])(r,o);return(0,h["default"])(c,a)||(l=!0),c}),d=(0,P["default"])((0,V["default"])(c),s);c.hasOwnProperty("")||s.hasOwnProperty("")||(d[""]=!1),l&&a(M["default"].setFieldsErrors(u,d))}}},{key:"handleValidSubmit",value:function(){var e=this.props,t=e.dispatch,r=e.model,n=e.modelValue,o=e.onSubmit,u=void 0===o?j["default"]:o;return t(M["default"].setPending(r)),u(n)}},{key:"handleInvalidSubmit",value:function(){var e=this.props,t=e.dispatch,r=e.model;t(M["default"].setSubmitFailed(r))}},{key:"handleReset",value:function(e){e&&e.preventDefault();var t=this.props,r=t.model,n=t.dispatch;n(M["default"].reset(r))}},{key:"handleSubmit",value:function(e){e&&e.preventDefault();var t=this.props,r=t.model,n=t.modelValue,o=t.formValue,u=t.onSubmit,a=t.dispatch,i=t.validators,f=t.errors,l=!o||o.valid;if(!i&&u&&l)return u(n),n;var c={onValid:this.handleValidSubmit,onInvalid:this.handleInvalidSubmit},s=i?(0,P["default"])((0,C["default"])(i),f):f;return a(M["default"].validateFieldsErrors(r,s,c)),n}},{key:"render",value:function(){var e=this.props,r=e.component,n=e.children,o=e.formValue,u=(0,S["default"])(this.props,Object.keys(t.propTypes)),a="function"==typeof n?n(o):n;return s["default"].createElement(r,f({},u,{onSubmit:this.handleSubmit,onReset:this.handleReset,ref:this.attachNode}),a)}}]),t}(c.Component);B.propTypes={component:c.PropTypes.any,validators:c.PropTypes.object,errors:c.PropTypes.object,validateOn:c.PropTypes.oneOf(["change","submit"]),model:c.PropTypes.string.isRequired,modelValue:c.PropTypes.any,formValue:c.PropTypes.object,onSubmit:c.PropTypes.func,dispatch:c.PropTypes.func,children:c.PropTypes.node},B.defaultProps={validateOn:"change",component:"form"},t["default"]=(0,p["default"])(i)(B)},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r={type:null};t["default"]=r},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"];t["default"]=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){return u({},e,{get valid(){return(0,i["default"])(e)},get pending(){return(0,l["default"])(e)},get touched(){return(0,s["default"])(e)},get retouched(){return(0,p["default"])(e)}})}Object.defineProperty(t,"__esModule",{value:!0}),t.isRetouched=t.isTouched=t.isPending=t.isValid=void 0;var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e};t["default"]=o;var a=r(11),i=n(a),f=r(80),l=n(f),c=r(82),s=n(c),d=r(81),p=n(d);t.isValid=i["default"],t.isPending=l["default"],t.isTouched=s["default"],t.isRetouched=p["default"]},function(e,t){"use strict";function r(e){return!!e&&(e.$form?Object.keys(e).some(function(t){return r(e[t])}):e.pending)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t){"use strict";function r(e){return!!e&&(e.$form?Object.keys(e).some(function(t){return r(e[t])}):e.retouched)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t){"use strict";function r(e){return!!e&&(e.$form?Object.keys(e).some(function(t){return r(e[t])}):e.touched)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){if(t.type!==a["default"].BLUR&&t.type!==a["default"].SET_TOUCHED)return e;var n=(0,c["default"])(e,r).$form;return(0,f["default"])(e,r,function(e){return{focus:t.type!==a["default"].BLUR&&e.focus,touched:!0,retouched:!(!n.submitted&&!n.submitFailed)}})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(1),a=n(u),i=r(5),f=n(i),l=r(98),c=n(l)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r=void 0,n=t.value,u=t.removeKeys,f=t.silent;if((0,h["default"])(e.value,n))return e; if(f)return s["default"].set(e,"value",n);if(u){var l=function(){var t=[];return Object.keys(e).forEach(function(r){~u.indexOf(+r)||"$form"===r||(t[r]=e[r])}),{v:i({},(0,g["default"])(t),{$form:e.$form})}}();if("object"===("undefined"==typeof l?"undefined":a(l)))return l.v}if(Array.isArray(n))r=function(e,t){return Array.prototype.map.call(e,t).filter(function(e){return!!e})};else{if(!(0,b["default"])(n))return s["default"].merge(e,{value:n,pristine:!1,validated:!1,retouched:!!e.submitted||e.retouched});r=function(e,t){return(0,P["default"])(e,t)}}var c=r(n,function(t,r){var n=e[r];return!!n&&(Object.hasOwnProperty.call(n,"$form")?o(n,t):(0,h["default"])(t,n.value)?n:s["default"].merge(n,{value:t,pristine:!1,validated:!1,retouched:!!e.submitted||n.retouched}))}),d=s["default"].merge(e.$form||O.initialFieldState,{pristine:!1,validated:!1,retouched:!!e.submitted||(e.$form||O.initialFieldState).retouched});return s["default"].set(c,"$form",s["default"].set(d,"value",n))}function u(e,t,r){if(t.type!==l["default"].CHANGE)return e;var n=(0,p["default"])(e,r,O.initialFieldState),u=o(n,t);return r.length?s["default"].setIn(e,r,u):u}Object.defineProperty(t,"__esModule",{value:!0});var a="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},i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e};t["default"]=u;var f=r(1),l=n(f),c=r(9),s=n(c),d=r(2),p=n(d),v=r(12),h=n(v),y=r(3),b=n(y),m=r(67),g=n(m),_=r(4),P=n(_),O=r(7)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t.type!==a["default"].FOCUS?e:(0,f["default"])(e,r,{focus:!0})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(1),a=n(u),i=r(5),f=n(i)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t.type!==a["default"].SET_PENDING?e:(0,f["default"])(e,r,function(){return{pending:t.pending,submitted:!1,submitFailed:!1,retouched:!1}})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(1),a=n(u),i=r(5),f=n(i)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t.type!==a["default"].RESET&&t.type!==a["default"].SET_INITIAL?e:(0,f["default"])(e,r,l.initialFieldState,l.initialFieldState)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(1),a=n(u),i=r(5),f=n(i),l=r(7)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t.type!==a["default"].RESET_VALIDITY?e:(0,f["default"])(e,r,{validity:l.initialFieldState.validity,errors:l.initialFieldState.errors},{validity:l.initialFieldState.validity,errors:l.initialFieldState.errors})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(1),a=n(u),i=r(5),f=n(i),l=r(7)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t.type!==a["default"].SET_DIRTY?e:(0,f["default"])(e,r,{pristine:!1})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(1),a=n(u),i=r(5),f=n(i)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t.type!==a["default"].SET_PRISTINE?e:(0,f["default"])(e,r,{pristine:!0},{pristine:!0})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(1),a=n(u),i=r(5),f=n(i)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function u(e,t,r){var n;if(t.type===s["default"].SET_FIELDS_VALIDITY)return(0,i["default"])(t.fieldsValidity,function(e,r){return l["default"].setValidity(r,e,t.options)}).reduce(function(e,t){return u(e,t,(0,P["default"])(t.model))},e);if(t.type===s["default"].SET_VALIDATING)return(0,g["default"])(e,r,{validating:t.validating,validated:!t.validating});if(t.type!==s["default"].SET_VALIDITY&&t.type!==s["default"].SET_ERRORS)return e;var a=t.type===s["default"].SET_ERRORS,f=a?t.errors:t.validity,c=(0,p["default"])(f)?(0,h["default"])(f,b["default"]):!f;return(0,g["default"])(e,r,(n={},o(n,a?"errors":"validity",f),o(n,a?"validity":"errors",c),o(n,"validating",!1),o(n,"validated",!0),n))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=u;var a=r(53),i=n(a),f=r(43),l=n(f),c=r(1),s=n(c),d=r(3),p=n(d),v=r(4),h=n(v),y=r(99),b=n(y),m=r(5),g=n(m),_=r(19),P=n(_)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t.type!==a["default"].SET_SUBMIT_FAILED?e:(0,f["default"])(e,r,function(e){return{pending:!1,submitted:e.submitted&&!t.submitFailed,submitFailed:!!t.submitFailed,touched:!0,retouched:!1}})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(1),a=n(u),i=r(5),f=n(i)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){if(t.type!==a["default"].SET_SUBMITTED)return e;var n=!!t.submitted;return(0,f["default"])(e,r,function(e){return{pending:!1,submitted:n,submitFailed:!n&&e.submitFailed,touched:!0,retouched:!1}},function(e,t){return{submitted:n,submitFailed:!n&&t.submitFailed,retouched:!1}})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(1),a=n(u),i=r(5),f=n(i)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t.type!==a["default"].SET_UNTOUCHED?e:(0,f["default"])(e,r,function(){return{focus:!1,touched:!1}})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(1),a=n(u),i=r(5),f=n(i)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function u(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],r=Object.keys(e),n={},u={},i=a({},h,t),l=i.key,s=i.plugins;return r.forEach(function(t){var r=e[t];if("function"==typeof r){var o=void 0;try{o=r(void 0,v)}catch(a){o=null}n[t]=(0,f["default"])(r,t),u[t]=o}else n[t]=(0,c["default"])(t,r),u[t]=r}),(0,p.combineReducers)(a({},n,o({},l,(0,d["default"])("",u,{plugins:s}))))}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e};t["default"]=u;var i=r(45),f=n(i),l=r(30),c=n(l),s=r(7),d=n(s),p=r(41),v={type:null},h={key:"forms",plugins:[]}},function(e,t){"use strict";function r(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return function(e,r){return t.reduceRight(function(e,t){return t(e,r)},e)}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t){"use strict";function r(e,t){var r=void 0;return Object.keys(e).some(function(n){var o=t(e[n],n,e);return!!o&&(r=n,!0)}),r}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r=t.slice(0,-1);return r.length?(0,a["default"])(e,r):e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(2),a=n(u)},function(e,t){"use strict";function r(e){return!e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){return"function"==typeof e?function(t){return!e(t)}:(0,a["default"])(e,o)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(4),a=n(u)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=Array.isArray(e)?f["default"]:c["default"];return(0,a["default"])(e)?t(e,o):!!e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(3),a=n(u),i=r(117),f=n(i),l=r(133),c=n(l)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){return(0,a["default"])(e)?(0,f["default"])(e,o):!!e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(3),a=n(u),i=r(120),f=n(i)},function(e,t){"use strict";function r(e,t){var r=[[],[]];return e.forEach(function(n,o){t(n,o,e)?r[0].push(n):r[1].push(n)}),r}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(e===t)return!0;var r=(0,a["default"])(e),n=(0,a["default"])(t),o=n.every(function(e,t){return r[t]===e});return o}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(70),a=n(u)},function(e,t){"use strict";function r(e){return function(t){return t&&t.persist&&t.persist(),e(t),t}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){return!(0,i["default"])(e.props,t,["children"])||u.Children.count(e.props.children)!==u.Children.count(t.children)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(8),a=r(12),i=n(a)},function(e,t){"use strict";function r(e,t){return e===t?0!==e||1/e===1/t:e!==e&&t!==t}function n(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),u=Object.keys(t);if(n.length!==u.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;e.exports=n},function(e,t){"use strict";var r={childContextTypes:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,mixins:!0,propTypes:!0,type:!0},n={name:!0,length:!0,prototype:!0,caller:!0,arguments:!0,arity:!0},o="function"==typeof Object.getOwnPropertySymbols;e.exports=function(e,t,u){if("string"!=typeof t){var a=Object.getOwnPropertyNames(t);o&&(a=a.concat(Object.getOwnPropertySymbols(t)));for(var i=0;i<a.length;++i)if(!(r[a[i]]||n[a[i]]||u&&u[a[i]]))try{e[a[i]]=t[a[i]]}catch(f){}}return e}},function(e,t,r){"use strict";var n=function(e,t,r,n,o,u,a,i){if(!e){var f;if(void 0===t)f=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var l=[r,n,o,u,a,i],c=0;f=new Error(t.replace(/%s/g,function(){return l[c++]})),f.name="Invariant Violation"}throw f.framesToPop=1,f}};e.exports=n},function(e,t,r){function n(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}var o=r(147),u=r(148),a=r(149),i=r(150),f=r(151);n.prototype.clear=o,n.prototype["delete"]=u,n.prototype.get=a,n.prototype.has=i,n.prototype.set=f,e.exports=n},function(e,t,r){function n(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}var o=r(157),u=r(158),a=r(159),i=r(160),f=r(161);n.prototype.clear=o,n.prototype["delete"]=u,n.prototype.get=a,n.prototype.has=i,n.prototype.set=f,e.exports=n},function(e,t,r){var n=r(62),o=r(38),u=n(o,"Map");e.exports=u},function(e,t,r){function n(e){var t=-1,r=e?e.length:0;for(this.__data__=new o;++t<r;)this.add(e[t])}var o=r(55),u=r(169),a=r(170);n.prototype.add=n.prototype.push=u,n.prototype.has=a,e.exports=n},function(e,t){function r(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}e.exports=r},function(e,t,r){function n(e,t){var r=e?e.length:0;return!!r&&o(e,t,0)>-1}var o=r(126);e.exports=n},function(e,t){function r(e,t,r){for(var n=-1,o=e?e.length:0;++n<o;)if(r(t,e[n]))return!0;return!1}e.exports=r},function(e,t){function r(e,t){for(var r=-1,n=e?e.length:0;++r<n;)if(t(e[r],r,e))return!0;return!1}e.exports=r},function(e,t){function r(e,t,r){return e===e&&(void 0!==r&&(e=e<=r?e:r),void 0!==t&&(e=e>=t?e:t)),e}e.exports=r},function(e,t,r){function n(e,t,r,n){var s=-1,d=u,p=!0,v=e.length,h=[],y=t.length;if(!v)return h;r&&(t=i(t,f(r))),n?(d=a,p=!1):t.length>=c&&(d=l,p=!1,t=new o(t));e:for(;++s<v;){var b=e[s],m=r?r(b):b;if(b=n||0!==b?b:0,p&&m===m){for(var g=y;g--;)if(t[g]===m)continue e;h.push(b)}else d(t,m,n)||h.push(b)}return h}var o=r(113),u=r(115),a=r(116),i=r(13),f=r(135),l=r(136),c=200;e.exports=n},function(e,t,r){function n(e,t){var r=!0;return o(e,function(e,n,o){return r=!!t(e,n,o)}),r}var o=r(36);e.exports=n},function(e,t){function r(e,t,r,n){for(var o=e.length,u=r+(n?1:-1);n?u--:++u<o;)if(t(e[u],u,e))return u;return-1}e.exports=r},function(e,t,r){var n=r(141),o=n();e.exports=o},function(e,t,r){function n(e,t){return e&&o(e,t,u)}var o=r(122),u=r(177);e.exports=n},function(e,t,r){function n(e,t){t=u(t,e)?[t]:o(t);for(var r=0,n=t.length;null!=e&&r<n;)e=e[a(t[r++])];return r&&r==n?e:void 0}var o=r(137),u=r(154),a=r(23);e.exports=n},function(e,t,r){function n(e,t,r){var n=t(e);return u(e)?n:o(n,r(e))}var o=r(35),u=r(6);e.exports=n},function(e,t,r){function n(e,t,r){if(t!==t)return o(e,u,r);for(var n=r-1,a=e.length;++n<a;)if(e[n]===t)return n;return-1}var o=r(121),u=r(127);e.exports=n},function(e,t){function r(e){return e!==e}e.exports=r},function(e,t,r){function n(e){if(!i(e)||a(e))return!1;var t=o(e)||u(e)?v:c;return t.test(f(e))}var o=r(40),u=r(64),a=r(156),i=r(24),f=r(171),l=/[\\^$.*+?()[\]{}|]/g,c=/^\[object .+?Constructor\]$/,s=Object.prototype,d=Function.prototype.toString,p=s.hasOwnProperty,v=RegExp("^"+d.call(p).replace(l,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");e.exports=n},function(e,t,r){function n(e){if(!o(e))return u(e);var t=[];for(var r in Object(e))i.call(e,r)&&"constructor"!=r&&t.push(r);return t}var o=r(65),u=r(167),a=Object.prototype,i=a.hasOwnProperty;e.exports=n},function(e,t,r){function n(e){if(!o(e))return a(e);var t=u(e),r=[];for(var n in e)("constructor"!=n||!t&&f.call(e,n))&&r.push(n);return r}var o=r(24),u=r(65),a=r(168),i=Object.prototype,f=i.hasOwnProperty;e.exports=n},function(e,t,r){function n(e,t){var r=-1,n=u(e)?Array(e.length):[];return o(e,function(e,o,u){n[++r]=t(e,o,u)}),n}var o=r(36),u=r(15);e.exports=n},function(e,t){function r(e,t,r){for(var n=-1,o=t.length,u={};++n<o;){var a=t[n],i=e[a];r(i,a)&&(u[a]=i)}return u}e.exports=r},function(e,t,r){function n(e,t){var r;return o(e,function(e,n,o){return r=t(e,n,o),!r}),!!r}var o=r(36);e.exports=n},function(e,t){function r(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}e.exports=r},function(e,t){function r(e){return function(t){return e(t)}}e.exports=r},function(e,t){function r(e,t){return e.has(t)}e.exports=r},function(e,t,r){function n(e){return o(e)?e:u(e)}var o=r(6),u=r(66);e.exports=n},function(e,t){function r(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}e.exports=r},function(e,t,r){var n=r(38),o=n["__core-js_shared__"];e.exports=o},function(e,t,r){function n(e,t){return function(r,n){if(null==r)return r;if(!o(r))return e(r,n);for(var u=r.length,a=t?u:-1,i=Object(r);(t?a--:++a<u)&&n(i[a],a,i)!==!1;);return r}}var o=r(15);e.exports=n},function(e,t){function r(e){return function(t,r,n){for(var o=-1,u=Object(t),a=n(t),i=a.length;i--;){var f=a[e?i:++o];if(r(u[f],f,u)===!1)break}return t}}e.exports=r},function(e,t){(function(t){var r="object"==typeof t&&t&&t.Object===Object&&t;e.exports=r}).call(t,function(){return this}())},function(e,t,r){function n(e){return o(e,a,u)}var o=r(125),u=r(145),a=r(178);e.exports=n},function(e,t,r){var n=r(37),o=r(69),u=Object.getOwnPropertySymbols,a=u?n(u,Object):o;e.exports=a},function(e,t,r){var n=r(35),o=r(63),u=r(144),a=r(69),i=Object.getOwnPropertySymbols,f=i?function(e){for(var t=[];e;)n(t,u(e)),e=o(e);return t}:a;e.exports=f},function(e,t){function r(e,t){return null==e?void 0:e[t]}e.exports=r},function(e,t,r){function n(){this.__data__=o?o(null):{}}var o=r(22);e.exports=n},function(e,t){function r(e){return this.has(e)&&delete this.__data__[e]}e.exports=r},function(e,t,r){function n(e){var t=this.__data__;if(o){var r=t[e];return r===u?void 0:r}return i.call(t,e)?t[e]:void 0}var o=r(22),u="__lodash_hash_undefined__",a=Object.prototype,i=a.hasOwnProperty;e.exports=n},function(e,t,r){function n(e){var t=this.__data__;return o?void 0!==t[e]:a.call(t,e)}var o=r(22),u=Object.prototype,a=u.hasOwnProperty;e.exports=n},function(e,t,r){function n(e,t){var r=this.__data__;return r[e]=o&&void 0===t?u:t,this}var o=r(22),u="__lodash_hash_undefined__";e.exports=n},function(e,t,r){function n(e){return a(e)||u(e)||!!(i&&e&&e[i])}var o=r(56),u=r(68),a=r(6),i=o?o.isConcatSpreadable:void 0;e.exports=n},function(e,t){function r(e,t){return t=null==t?n:t,!!t&&("number"==typeof e||o.test(e))&&e>-1&&e%1==0&&e<t}var n=9007199254740991,o=/^(?:0|[1-9]\d*)$/;e.exports=r},function(e,t,r){function n(e,t){if(o(e))return!1;var r=typeof e;return!("number"!=r&&"symbol"!=r&&"boolean"!=r&&null!=e&&!u(e))||i.test(e)||!a.test(e)||null!=t&&e in Object(t)}var o=r(6),u=r(16),a=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,i=/^\w*$/;e.exports=n},function(e,t){function r(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}e.exports=r},function(e,t,r){function n(e){return!!u&&u in e}var o=r(139),u=function(){var e=/[^.]+$/.exec(o&&o.keys&&o.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();e.exports=n},function(e,t){function r(){this.__data__=[]}e.exports=r},function(e,t,r){function n(e){var t=this.__data__,r=o(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():a.call(t,r,1),!0}var o=r(20),u=Array.prototype,a=u.splice;e.exports=n},function(e,t,r){function n(e){var t=this.__data__,r=o(t,e);return r<0?void 0:t[r][1]}var o=r(20);e.exports=n},function(e,t,r){function n(e){return o(this.__data__,e)>-1}var o=r(20);e.exports=n},function(e,t,r){function n(e,t){var r=this.__data__,n=o(r,e);return n<0?r.push([e,t]):r[n][1]=t,this}var o=r(20);e.exports=n},function(e,t,r){function n(){this.__data__={hash:new o,map:new(a||u),string:new o}}var o=r(110),u=r(111),a=r(112);e.exports=n},function(e,t,r){function n(e){return o(this,e)["delete"](e)}var o=r(21);e.exports=n},function(e,t,r){function n(e){return o(this,e).get(e)}var o=r(21);e.exports=n},function(e,t,r){function n(e){return o(this,e).has(e)}var o=r(21);e.exports=n},function(e,t,r){function n(e,t){return o(this,e).set(e,t),this}var o=r(21);e.exports=n},function(e,t,r){var n=r(37),o=n(Object.keys,Object);e.exports=o},function(e,t){function r(e){var t=[];if(null!=e)for(var r in Object(e))t.push(r);return t}e.exports=r},function(e,t){function r(e){return this.__data__.set(e,n),this}var n="__lodash_hash_undefined__";e.exports=r},function(e,t){function r(e){return this.__data__.has(e)}e.exports=r},function(e,t){function r(e){if(null!=e){try{return n.call(e)}catch(t){}try{return e+""}catch(t){}}return""}var n=Function.prototype.toString;e.exports=r},function(e,t){function r(e,t){return e===t||e!==e&&t!==t}e.exports=r},function(e,t,r){function n(e,t,r){var n=null==e?void 0:o(e,t);return void 0===n?r:n}var o=r(124);e.exports=n},function(e,t,r){function n(e){return u(e)&&o(e)}var o=r(15),u=r(25);e.exports=n},function(e,t){function r(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=n}var n=9007199254740991;e.exports=r},function(e,t,r){function n(e){return"string"==typeof e||!o(e)&&u(e)&&f.call(e)==a}var o=r(6),u=r(25),a="[object String]",i=Object.prototype,f=i.toString;e.exports=n},function(e,t,r){function n(e){return a(e)?o(e):u(e)}var o=r(57),u=r(129),a=r(15);e.exports=n},function(e,t,r){function n(e){return a(e)?o(e,!0):u(e)}var o=r(57),u=r(130),a=r(15);e.exports=n},function(e,t,r){function n(e,t){if("function"!=typeof e||t&&"function"!=typeof t)throw new TypeError(u);var r=function(){var n=arguments,o=t?t.apply(this,n):n[0],u=r.cache;if(u.has(o))return u.get(o);var a=e.apply(this,n);return r.cache=u.set(o,a),a};return r.cache=new(n.Cache||o),r}var o=r(55),u="Expected a function";n.Cache=o,e.exports=n},function(e,t,r){var n=r(13),o=r(58),u=r(59),a=r(60),i=r(23),f=a(function(e,t){return null==e?{}:u(e,n(o(t,1),i))});e.exports=f},function(e,t,r){function n(e){if(!e)return 0===e?e:0;if(e=o(e),e===u||e===-u){var t=e<0?-1:1;return t*a}return e===e?e:0}var o=r(183),u=1/0,a=1.7976931348623157e308;e.exports=n},function(e,t,r){function n(e){var t=o(e),r=t%1;return t===t?r?t-r:t:0}var o=r(181);e.exports=n},function(e,t,r){function n(e){if("number"==typeof e)return e;if(a(e))return i;if(u(e)){var t=o(e.valueOf)?e.valueOf():e;e=u(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(f,"");var r=c.test(e);return r||s.test(e)?d(e.slice(2),r?2:8):l.test(e)?i:+e}var o=r(40),u=r(24),a=r(16),i=NaN,f=/^\s+|\s+$/g,l=/^[-+]0x[0-9a-f]+$/i,c=/^0b[01]+$/i,s=/^0o[0-7]+$/i,d=parseInt;e.exports=n},function(e,t){"use strict";function r(e,t){if(e===t)return!0;var r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(var o=Object.prototype.hasOwnProperty,u=0;u<r.length;u++)if(!o.call(t,r[u])||e[r[u]]!==t[r[u]])return!1;return!0}t.__esModule=!0,t["default"]=r},function(e,t,r){"use strict";t.__esModule=!0;var n=r(8);t["default"]=n.PropTypes.shape({subscribe:n.PropTypes.func.isRequired,dispatch:n.PropTypes.func.isRequired,getState:n.PropTypes.func.isRequired})},function(e,t){"use strict";function r(e){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(e);try{throw new Error(e)}catch(t){}}t.__esModule=!0,t["default"]=r},function(e,t,r){"use strict";function n(e){return function(t){return(0,o.bindActionCreators)(e,t)}}t.__esModule=!0,t["default"]=n;var o=r(41)},function(e,t){e.exports=r}])});
src/js/components/Box/stories/Animation.js
HewlettPackard/grommet
import React from 'react'; import { Grommet, Box, Grid } from 'grommet'; import { grommet } from '../../../themes'; export const Animation = () => ( <Grommet theme={grommet}> <Box pad="medium"> <Grid columns="small" gap="medium"> {[ 'fadeIn', 'fadeOut', 'jiggle', 'pulse', 'rotateRight', 'rotateLeft', 'slideUp', 'slideDown', 'slideLeft', 'slideRight', 'zoomIn', 'zoomOut', ].map(animation => ( <Box key={animation} pad="large" background="brand" animation={{ type: animation, duration: 4000 }} align="center" > {animation} </Box> ))} </Grid> </Box> </Grommet> ); export default { title: 'Layout/Box/Animation', };
ajax/libs/vue/2.4.4/vue.runtime.esm.js
froala/cdnjs
/*! * Vue.js v2.4.4 * (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' } var _toString = Object.prototype.toString; /** * 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(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,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. */ /** * 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' ]; /* */ 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 formatComponentName = (null); // work around flow check 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 name = typeof vm === 'string' ? vm : typeof vm === 'function' && vm.options ? vm.options.name : vm._isVue ? vm.$options.name || vm.$options._componentTag : vm.name; var file = vm._isVue && vm.$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 }; var 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 (config.errorHandler) { config.errorHandler.call(null, err, vm, info); } else { 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 MutationObserver */ // 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](); } } // the nextTick behavior leverages the microtask queue, which can be accessed // via either native Promise.then or MutationObserver. // MutationObserver has wider support, however it is seriously bugged in // UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It // completely stops working after triggering a few times... so, if native // Promise is available, we will use it: /* istanbul ignore if */ if (typeof Promise !== 'undefined' && isNative(Promise)) { var p = Promise.resolve(); var logError = function (err) { console.error(err); }; timerFunc = function () { p.then(nextTickHandler).catch(logError); // in problematic UIWebViews, Promise.then doesn't completely break, but // it can get stuck in a weird state where callbacks are pushed into the // microtask queue but the queue isn't being flushed, until the browser // needs to do some other work, e.g. handle a timer. Therefore we can // "force" the microtask queue to be flushed by adding an empty timer. if (isIOS) { setTimeout(noop); } }; } else if (!isIE && typeof MutationObserver !== 'undefined' && ( isNative(MutationObserver) || // PhantomJS and iOS 7.x MutationObserver.toString() === '[object MutationObserverConstructor]' )) { // use MutationObserver where native Promise is not available, // e.g. PhantomJS, iOS7, Android 4.4 var counter = 1; var observer = new MutationObserver(nextTickHandler); var textNode = document.createTextNode(String(counter)); observer.observe(textNode, { characterData: true }); timerFunc = function () { counter = (counter + 1) % 2; textNode.data = String(counter); }; } else { // fallback to setTimeout /* istanbul ignore next */ 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(); } if (!cb && typeof Promise !== 'undefined') { return new Promise(function (resolve, reject) { _resolve = resolve; }) } } })(); var _Set; /* istanbul ignore if */ 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$1 = 0; /** * A dep is an observable that can have multiple * directives subscribing to it. */ var Dep = function Dep () { this.id = uid$1++; 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(); } /* * 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$$1(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)) { 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$$1 ( 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$$1(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) { var res = Object.create(parentVal || null); return childVal ? extend(res, childVal) : 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) { // 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 (!parentVal) { return childVal } var ret = {}; extend(ret, parentVal); for (var key in childVal) { var parent = ret[key]; var child = childVal[key]; if (parent && !Array.isArray(parent)) { parent = [parent]; } ret[key] = 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) { 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) { 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 }; } } options.props = res; } /** * Normalize all injections into Object-based format */ function normalizeInject (options) { var inject = options.inject; if (Array.isArray(inject)) { var normalized = options.inject = {}; for (var i = 0; i < inject.length; i++) { normalized[inject[i]] = inject[i]; } } } /** * 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 }; } } } } /** * 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); normalizeInject(child); 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 ' + Object.prototype.toString.call(value).slice(8, -1) + '.', 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 } /* */ /* 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 to declare reactive data " + "properties in the data option.", target ); }; var hasProxy = typeof Proxy !== 'undefined' && Proxy.toString().match(/native code/); if (hasProxy) { var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta'); 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 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); }; } } /* */ 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.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: {} }; // 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 } /* */ 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; var plain = !(passive || once$$1 || capture); return { name: name, plain: plain, 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 } // #6552 function prioritizePlainEvents (a, b) { return a.plain ? -1 : b.plain ? 1 : 0 } function updateListeners ( on, oldOn, add, remove$$1, vm ) { var name, cur, old, event; var toAdd = []; var hasModifier = false; for (name in on) { cur = on[name]; old = oldOn[name]; event = normalizeEvent(name); if (!event.plain) { hasModifier = true; } 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); } event.handler = cur; toAdd.push(event); } else if (cur !== old) { old.fns = cur; on[name] = old; } } if (toAdd.length) { if (hasModifier) { toAdd.sort(prioritizePlainEvents); } for (var i = 0; i < toAdd.length; i++) { var event$1 = toAdd[i]; add(event$1.name, event$1.handler, event$1.once, event$1.capture, event$1.passive); } } 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, last; for (i = 0; i < children.length; i++) { c = children[i]; if (isUndef(c) || typeof c === 'boolean') { continue } last = res[res.length - 1]; // nested if (Array.isArray(c)) { res.push.apply(res, normalizeArrayChildren(c, ((nestedIndex || '') + "_" + i))); } 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 (last).text += String(c); } else if (c !== '') { // convert primitive to vnode res.push(createTextVNode(c)); } } else { if (isTextNode(c) && isTextNode(last)) { // merge adjacent text nodes res[res.length - 1] = 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 && comp.default) { 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$$1) { if (once$$1) { 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; } }; } 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((name + " render"), startTag, endTag); mark(startTag); vm._update(vnode, hydrating); mark(endTag); measure((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 checkOptionType (vm, name) { var option = vm.$options[name]; if (!isPlainObject(option)) { warn( ("component option \"" + name + "\" should be an object."), vm ); } } 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') { if (isReservedAttribute(key) || config.isReservedAttr(key)) { warn( ("\"" + key + "\" is a reserved attribute and cannot be used as component prop."), vm ); } defineReactive$$1(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$$1(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) } catch (e) { handleError(e, vm, "data()"); return {} } } var computedWatcherOptions = { lazy: true }; function initComputed (vm, computed) { process.env.NODE_ENV !== 'production' && checkOptionType(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) { process.env.NODE_ENV !== 'production' && checkOptionType(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) { process.env.NODE_ENV !== 'production' && checkOptionType(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$$1(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$$1(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]; var source = vm; while (source) { if (source._provided && provideKey in source._provided) { result[key] = source._provided[provideKey]; break } source = source.$parent; } if (process.env.NODE_ENV !== 'production' && !source) { warn(("Injection \"" + key + "\" not found"), vm); } } return result } } /* */ function createFunctionalComponent ( Ctor, propsData, data, context, children ) { var props = {}; var propOptions = Ctor.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); } } // ensure the createElement function in functional components // gets a unique context - this is necessary for correct named slot check var _context = Object.create(context); var h = function (a, b, c, d) { return createElement(_context, a, b, c, d, true); }; var vnode = Ctor.options.render.call(null, h, { data: data, props: props, children: children, parent: context, listeners: data.on || emptyObject, injections: resolveInject(Ctor.options.inject, context), slots: function () { return resolveSlots(children, context); } }); if (vnode instanceof VNode) { vnode.functionalContext = context; vnode.functionalOptions = Ctor.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) { vnode.ns = ns; if (vnode.tag === 'foreignObject') { // use default namespace inside foreignObject return } 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)) { applyNS(child, ns); } } } } /* */ /** * 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) { 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. */ function checkKeyCodes ( eventKeyCode, key, builtInAlias ) { var keyCodes = config.keyCodes[key] || builtInAlias; if (Array.isArray(keyCodes)) { return keyCodes.indexOf(eventKeyCode) === -1 } else { return keyCodes !== eventKeyCode } } /* */ /** * 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 ) { var tree = this._staticTrees[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 = this._staticTrees[index] = this.$options.staticRenderFns[index].call(this._renderProxy); 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(ours, existing) : ours; } } } return data } /* */ function initRender (vm) { vm._vnode = null; // the root of the child tree vm._staticTrees = null; var parentVnode = vm.$vnode = vm.$options._parentVnode; // the placeholder node in parent tree var renderContext = parentVnode && parentVnode.context; vm.$slots = resolveSlots(vm.$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$$1(vm, '$attrs', parentData && parentData.attrs || emptyObject, function () { !isUpdatingChildComponent && warn("$attrs is readonly.", vm); }, true); defineReactive$$1(vm, '$listeners', vm.$options._parentListeners || emptyObject, function () { !isUpdatingChildComponent && warn("$listeners is readonly.", vm); }, true); } else { defineReactive$$1(vm, '$attrs', parentData && parentData.attrs || emptyObject, null, true); defineReactive$$1(vm, '$listeners', vm.$options._parentListeners || emptyObject, null, true); } } function renderMixin (Vue) { 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 staticRenderFns = ref.staticRenderFns; 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; if (staticRenderFns && !vm._staticTrees) { vm._staticTrees = []; } // 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 function"); // return error render result, // or previous vnode to prevent render error causing blank component /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { vnode = vm.$options.renderError ? vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e) : 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 }; // internal render helpers. // these are exposed on the instance prototype to reduce generated render // code size. Vue.prototype._o = markOnce; Vue.prototype._n = toNumber; Vue.prototype._s = toString; Vue.prototype._l = renderList; Vue.prototype._t = renderSlot; Vue.prototype._q = looseEqual; Vue.prototype._i = looseIndexOf; Vue.prototype._m = renderStatic; Vue.prototype._f = resolveFilter; Vue.prototype._k = checkKeyCodes; Vue.prototype._b = bindObjectProps; Vue.prototype._v = createTextVNode; Vue.prototype._e = createEmptyVNode; Vue.prototype._u = resolveScopedSlots; Vue.prototype._g = bindObjectListeners; } /* */ var uid = 0; function initMixin (Vue) { Vue.prototype._init = function (options) { var vm = this; // a uid vm._uid = uid++; var startTag, endTag; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { startTag = "vue-perf-init:" + (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(((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 } }; }); } /* */ var patternTypes = [String, RegExp, Array]; 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 (cache, current, filter) { for (var key in cache) { var cachedNode = cache[key]; if (cachedNode) { var name = getComponentName(cachedNode.componentOptions); if (name && !filter(name)) { if (cachedNode !== current) { pruneCacheEntry(cachedNode); } cache[key] = null; } } } } function pruneCacheEntry (vnode) { if (vnode) { vnode.componentInstance.$destroy(); } } var KeepAlive = { name: 'keep-alive', abstract: true, props: { include: patternTypes, exclude: patternTypes }, created: function created () { this.cache = Object.create(null); }, destroyed: function destroyed () { var this$1 = this; for (var key in this$1.cache) { pruneCacheEntry(this$1.cache[key]); } }, watch: { include: function include (val) { pruneCache(this.cache, this._vnode, function (name) { return matches(val, name); }); }, exclude: function exclude (val) { pruneCache(this.cache, this._vnode, 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 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 (this.cache[key]) { vnode.componentInstance = this.cache[key].componentInstance; } else { this.cache[key] = 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$$1 }; 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.4.4'; /* */ // 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 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$$1 () { if (--remove$$1.listeners === 0) { removeNode(childElm); } } remove$$1.listeners = listeners; return remove$$1 } 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.indexOf(tag) > -1) && 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; 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 && 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, elmToMove, 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 { elmToMove = oldCh[idxInOld]; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && !elmToMove) { 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(elmToMove, newStartVnode)) { patchVnode(elmToMove, newStartVnode, insertedVnodeQueue); oldCh[idxInOld] = undefined; canMove && nodeOps.insertBefore(parentElm, elmToMove.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](); } } } 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] /* istanbul ignore if */ if (isIE9 && 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 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) } } /* */ /* */ /** * Cross-platform code generation for component v-model */ /** * Cross-platform codegen helper for generating v-model value assignment code. */ /** * parse directive model to do the array update transform. a[idx] = val => $$a.splice($$idx, 1, val) * * for loop possible cases: * * - test * - test[idx] * - test[test1[idx]] * - test["a"][idx] * - xxx.test[a[a].test1[idx]] * - test.xxx.a["asa"][test1[idx]] * */ var str; var index$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'; /* */ // 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) { var event; /* istanbul ignore if */ if (isDef(on[RANGE_TOKEN])) { // IE input[type=range] only supports `change` event event = isIE ? 'change' : 'input'; on[event] = [].concat(on[RANGE_TOKEN], on[event] || []); delete on[RANGE_TOKEN]; } if (isDef(on[CHECKBOX_RADIO_TOKEN])) { // Chrome fires microtasks in between click/change, leads to #4521 event = isChrome ? 'click' : 'change'; on[event] = [].concat(on[CHECKBOX_RADIO_TOKEN], on[event] || []); 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 } } 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, vnode, strCur)) { elm.value = strCur; } } else { elm[key] = cur; } } } // check platforms/web/util/attrs.js acceptValue function shouldUpdateValue ( elm, vnode, checkVal ) { return (!elm.composing && ( vnode.tag === '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$$1) { if (!def$$1) { return } /* istanbul ignore else */ if (typeof def$$1 === 'object') { var res = {}; if (def$$1.css !== false) { extend(res, autoCssTransition(def$$1.name || 'v')); } extend(res, def$$1); return res } else if (typeof def$$1 === 'string') { return autoCssTransition(def$$1) } } 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; 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 && (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 var body = document.body; var f = body.offsetHeight; // eslint-disable-line 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 */ setTimeout(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); /* */ export default Vue$3;
src/stories/QuickForm.basic.js
mazlix/react-form-simple-schema
import React from 'react'; import { storiesOf, action } from '@kadira/storybook'; import { MyRequestOrgSchema } from '../_fixture-schema-request-form'; import QuickForm from '../QuickForm'; require("!style!css!less!bootstrap/less/bootstrap.less"); storiesOf('QuickForm Basic', module) .add('just 2 parts of an object', () => ( <QuickForm schema={MyRequestOrgSchema} onValidSubmit={action('onValidSubmit')} onValid={action('onValid')} onInvalid={action('onInvalid')} canSubmit={ true } fields={['address.street','address.postalCode']} /> )) .add('fields as string: only name and email', () => ( <QuickForm schema={MyRequestOrgSchema} onValidSubmit={action('onValidSubmit')} onValid={action('onValid')} onInvalid={action('onInvalid')} fields="name,email" /> )) .add('fields as array: only name and email', () => ( <QuickForm schema={MyRequestOrgSchema} onValidSubmit={action('onValidSubmit')} onValid={action('onValid')} onInvalid={action('onInvalid')} fields={['name', 'email']} /> )) .add('omitFields: only first, last, and age', () => ( <QuickForm schema={MyRequestOrgSchema} onValidSubmit={action('onValidSubmit')} onValid={action('onValid')} onInvalid={action('onInvalid')} omitFields={[ 'userId', 'email', 'name', 'tags', 'favoriteYear', 'favoriteYears', 'phone', 'address', 'address.street', 'address.street2', 'address.city', 'address.state', 'address.postalCode', 'contacts', 'contacts.$', 'contacts.$.name', 'contacts.$.phone', 'message', ]} /> )) .add('whole schema', () => ( <QuickForm schema={MyRequestOrgSchema} onValidSubmit={action('onValidSubmit')} onValid={action('onValid')} onInvalid={action('onInvalid')} /> ));
src-rx/src/components/JsonConfigComponent/ConfigDatePicker.js
ioBroker/ioBroker.admin
import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import { KeyboardDatePicker } from '@material-ui/pickers'; import ConfigGeneric from './ConfigGeneric'; const styles = theme => ({ indeterminate: { opacity: 0.5 } }); class ConfigDatePicker extends ConfigGeneric { componentDidMount() { super.componentDidMount(); const value = ConfigGeneric.getValue(this.props.data, this.props.attr); this.setState({ value }); } renderItem(error, disabled, defaultValue) { return <KeyboardDatePicker fullWidth margin="normal" format={this.props.systemConfig.dateFormat.toLowerCase().replace('mm','MM')} error={!!error} disabled={!!disabled} value={this.state.value === null || this.state.value === undefined ? new Date() : this.state.value} KeyboardButtonProps={{ 'aria-label': 'change date', }} inputProps={{ maxLength: this.props.schema.maxLength || this.props.schema.max || undefined }} onChange={value => { this.setState({ value }, () => this.onChange(this.props.attr, value)); }} InputLabelProps={{ shrink: true, }} placeholder={this.getText(this.props.schema.placeholder)} label={this.getText(this.props.schema.label)} helperText={this.renderHelp(this.props.schema.help, this.props.schema.helpLink, this.props.schema.noTranslation)} />; } } ConfigDatePicker.propTypes = { socket: PropTypes.object.isRequired, themeType: PropTypes.string, themeName: PropTypes.string, style: PropTypes.object, className: PropTypes.string, data: PropTypes.object.isRequired, schema: PropTypes.object, onError: PropTypes.func, onChange: PropTypes.func, }; export default withStyles(styles)(ConfigDatePicker);
ajax/libs/rxjs/2.3.21/rx.lite.js
mscharl/cdnjs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: { Promise: root.Promise, }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; }, identity = Rx.helpers.identity = function (x) { return x; }, pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, just = Rx.helpers.just = function (value) { return function () { return value; }; }, defaultNow = Rx.helpers.defaultNow = Date.now, defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, defaultError = Rx.helpers.defaultError = function (err) { throw err; }, isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; }, asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, not = Rx.helpers.not = function (a) { return !a; }, isFunction = Rx.helpers.isFunction = (function () { var isFn = function (value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFn(/x/)) { isFn = function(value) { return typeof value == 'function' && toString.call(value) == '[object Function]'; }; } return isFn; }()); // Errors var sequenceContainsNoElements = 'Sequence contains no elements.'; var argumentOutOfRange = 'Argument out of range'; var objectDisposed = 'Object has been disposed'; function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } Rx.config.longStackSupport = false; var hasStacks = false; try { throw new Error(); } catch (e) { hasStacks = !!e.stack; } // All code after this point will be filtered from stack traces reported by RxJS var rStartingLine = captureLine(), rFileName; var STACK_JUMP_SEPARATOR = "From previous event:"; function makeStackTraceLong(error, observable) { // If possible, transform the error stack trace by removing Node and RxJS // cruft, then concatenating with the stack trace of `observable`. if (hasStacks && observable.stack && typeof error === "object" && error !== null && error.stack && error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1 ) { var stacks = []; for (var o = observable; !!o; o = o.source) { if (o.stack) { stacks.unshift(o.stack); } } stacks.unshift(error.stack); var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n"); error.stack = filterStackString(concatedStacks); } } function filterStackString(stackString) { var lines = stackString.split("\n"), desiredLines = []; for (var i = 0, len = lines.length; i < len; i++) { var line = lines[i]; if (!isInternalFrame(line) && !isNodeFrame(line) && line) { desiredLines.push(line); } } return desiredLines.join("\n"); } function isInternalFrame(stackLine) { var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine); if (!fileNameAndLineNumber) { return false; } var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1]; return fileName === rFileName && lineNumber >= rStartingLine && lineNumber <= rEndingLine; } function isNodeFrame(stackLine) { return stackLine.indexOf("(module.js:") !== -1 || stackLine.indexOf("(node.js:") !== -1; } function captureLine() { if (!hasStacks) { return; } try { throw new Error(); } catch (e) { var lines = e.stack.split("\n"); var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2]; var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine); if (!fileNameAndLineNumber) { return; } rFileName = fileNameAndLineNumber[0]; return fileNameAndLineNumber[1]; } } function getFileNameAndLineNumber(stackLine) { // Named functions: "at functionName (filename:lineNumber:columnNumber)" var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine); if (attempt1) { return [attempt1[1], Number(attempt1[2])]; } // Anonymous functions: "at filename:lineNumber:columnNumber" var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine); if (attempt2) { return [attempt2[1], Number(attempt2[2])]; } // Firefox style: "function@filename:lineNumber or @filename:lineNumber" var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine); if (attempt3) { return [attempt3[1], Number(attempt3[2])]; } } // Shim in iterator support var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Bug for mozilla version if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined }; var isIterable = Rx.helpers.isIterable = function (o) { return o[$iterator$] !== undefined; } var isArrayLike = Rx.helpers.isArrayLike = function (o) { return o && o.length !== undefined; } Rx.helpers.iterator = $iterator$; var deprecate = Rx.helpers.deprecate = function (name, alternative) { /*if (typeof console !== "undefined" && typeof console.warn === "function") { console.warn(name + ' is deprecated, use ' + alternative + ' instead.', new Error('').stack); }*/ } /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 supportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, stringProto = String.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; // Fix for Tessel if (!propertyIsEnumerable) { propertyIsEnumerable = objectProto.propertyIsEnumerable = function (key) { for (var k in this) { if (k === key) { return true; } } return false; }; } try { supportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch (e) { supportNodeClass = true; } var shadowedProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // https://code.google.com/p/v8/issues/detail?id=2291 var type = typeof value; return value && (type == 'function' || type == 'object') || false; } function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = shadowedProps.length; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = shadowedProps[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } var isArguments = function(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b : // but treat `-0` vs. `+0` as not equal (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; var result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var hasProp = {}.hasOwnProperty; var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; var addProperties = Rx.internals.addProperties = function (obj) { var sources = slice.call(arguments, 1); for (var i = 0, len = sources.length; i < len; i++) { var source = sources[i]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // Collections function IndexedItem(id, value) { this.id = id; this.value = value; } IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); c === 0 && (c = this.id - other.id); return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { +index || (index = 0); if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; delete this.items[this.length]; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { this.disposables = argsOrArray(arguments, 0); this.isDisposed = false; this.length = this.disposables.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Converts the existing CompositeDisposable to an array of disposables * @returns {Array} An array of disposable objects. */ CompositeDisposablePrototype.toArray = function () { return this.disposables.slice(0); }; /** * Provides a set of static methods for creating Disposables. * * @constructor * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () { function BooleanDisposable () { this.isDisposed = false; this.current = null; } var booleanDisposablePrototype = BooleanDisposable.prototype; /** * Gets the underlying disposable. * @return The underlying disposable. */ booleanDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ booleanDisposablePrototype.setDisposable = function (value) { var shouldDispose = this.isDisposed, old; if (!shouldDispose) { old = this.current; this.current = value; } old && old.dispose(); shouldDispose && value && value.dispose(); }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } old && old.dispose(); }; return BooleanDisposable; }()); var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable; /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed) { if (!this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed) { if (!this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { timeSpan < 0 && (timeSpan = 0); return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; (function (schedulerProto) { function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function scheduleInnerRecursive(action, self) { action(function(dt) { self(action, dt); }); } /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState({ first: state, second: action }, invokeRecImmediate); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, action); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) { if (typeof root.setInterval === 'undefined') { throw new Error('Periodic scheduling not supported.'); } var s = state; var id = root.setInterval(function () { s = action(s); }, period); return disposableCreate(function () { root.clearInterval(id); }); }; }(Scheduler.prototype)); /** Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } function scheduleRelative(state, dueTime, action) { var dt = normalizeTime(dueTime); while (dt - this.now() > 0) { } return action(this, state); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline (q) { var item; while (q.length > 0) { item = q.dequeue(); if (!item.isCancelled()) { // Note, do not schedule blocking work! while (item.dueTime - Scheduler.now() > 0) { } if (!item.isCancelled()) { item.invoke(); } } } } function scheduleNow(state, action) { return this.scheduleWithRelativeAndState(state, 0, action); } function scheduleRelative(state, dueTime, action) { var dt = this.now() + Scheduler.normalize(dueTime), si = new ScheduledItem(this, state, action, dt); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); try { runTrampoline(queue); } catch (e) { throw e; } finally { queue = null; } } else { queue.enqueue(si); } return si.disposable; } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); currentScheduler.scheduleRequired = function () { return !queue; }; currentScheduler.ensureTrampoline = function (action) { if (!queue) { this.schedule(action); } else { action(); } }; return currentScheduler; }()); var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); var scheduleMethod, clearMethod = noop; var localTimer = (function () { var localSetTimeout, localClearTimeout = noop; if ('WScript' in this) { localSetTimeout = function (fn, time) { WScript.Sleep(time); fn(); }; } else if (!!root.setTimeout) { localSetTimeout = root.setTimeout; localClearTimeout = root.clearTimeout; } else { throw new Error('No concurrency detected!'); } return { setTimeout: localSetTimeout, clearTimeout: localClearTimeout }; }()); var localSetTimeout = localTimer.setTimeout, localClearTimeout = localTimer.clearTimeout; (function () { var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate, clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && !reNative.test(clearImmediate) && clearImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('', '*'); root.onmessage = oldHandler; return isAsync; } // Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; var onGlobalPostMessage = function (event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); delete tasks[handleId]; } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; root.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(), channelTasks = {}, channelTaskId = 0; channel.port1.onmessage = function (event) { var id = event.data, action = channelTasks[id]; action(); delete channelTasks[id]; }; scheduleMethod = function (action) { var id = channelTaskId++; channelTasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return localSetTimeout(action, 0); }; clearMethod = localClearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = localSetTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { localClearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { return observerOrOnNext && typeof observerOrOnNext === 'object' ? this._acceptObservable(observerOrOnNext) : this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notifications * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ Notification.prototype.toObservable = function (scheduler) { var notification = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); notification.kind === 'N' && observer.onCompleted(); }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept (onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString () { return 'OnNext(' + this.value + ')'; } return function (value) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (e) { var notification = new Notification('E'); notification.exception = e; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { var notification = new Notification('C'); notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch (err) { observer.onError(err); return; } var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var currentItem; if (isDisposed) { return; } try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { observer.onCompleted(); return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { self(); }) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchError = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch (err) { observer.onError(err); return; } var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } var currentItem; try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { if (lastException) { observer.onError(lastException); } else { observer.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), function (exn) { lastException = exn; self(); }, observer.onCompleted.bind(observer))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableOf = Enumerable.of = function (source, selector, thisArg) { selector || (selector = identity); return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: selector.call(thisArg, source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler, thisArg) { return new AnonymousObserver(function (x) { return handler.call(thisArg, notificationCreateOnNext(x)); }, function (e) { return handler.call(thisArg, notificationCreateOnError(e)); }, function () { return handler.call(thisArg, notificationCreateOnCompleted()); }); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) { inherits(AbstractObserver, __super__); /** * Creates a new observer in a non-stopped state. */ function AbstractObserver() { this.isStopped = false; __super__.call(this); } /** * Notifies the observer of a new element in the sequence. * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) { inherits(AnonymousObserver, __super__); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { __super__.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (error) { this._onError(error); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { if (Rx.config.longStackSupport && hasStacks) { try { throw new Error(); } catch (e) { this.stack = e.stack.substring(e.stack.indexOf("\n") + 1); } var self = this; this._subscribe = function (observer) { var oldOnError = observer.onError.bind(observer); observer.onError = function (err) { makeStackTraceLong(err, self); oldOnError(err); }; return subscribe(observer); }; } else { this._subscribe = subscribe; } } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { return this._subscribe(typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onNext The function to invoke on each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnNext = function (onNext, thisArg) { return this._subscribe(observerCreate(arguments.length === 2 ? function(x) { onNext.call(thisArg, x); } : onNext)); }; /** * Subscribes to an exceptional condition in the sequence with an optional "this" argument. * @param {Function} onError The function to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnError = function (onError, thisArg) { return this._subscribe(observerCreate(null, arguments.length === 2 ? function(e) { onError.call(thisArg, e); } : onError)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnCompleted = function (onCompleted, thisArg) { return this._subscribe(observerCreate(null, null, arguments.length === 2 ? function() { onCompleted.call(thisArg); } : onCompleted)); }; return Observable; })(); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) { inherits(ScheduledObserver, __super__); function ScheduledObserver(scheduler, observer) { __super__.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (e) { var self = this; this.queue.push(function () { self.observer.onError(e); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); /** * Creates an array from an observable sequence. * @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { var source = this; return new AnonymousObservable(function(observer) { var arr = []; return source.subscribe( arr.push.bind(arr), observer.onError.bind(observer), function () { observer.onNext(arr); observer.onCompleted(); }); }, source); }; /** * Creates an observable sequence from a specified subscribe method implementation. * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe, parent) { return new AnonymousObservable(subscribe, parent); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; var maxSafeInteger = Math.pow(2, 53) - 1; function StringIterable(str) { this._s = s; } StringIterable.prototype[$iterator$] = function () { return new StringIterator(this._s); }; function StringIterator(str) { this._s = s; this._l = s.length; this._i = 0; } StringIterator.prototype[$iterator$] = function () { return this; }; StringIterator.prototype.next = function () { if (this._i < this._l) { var val = this._s.charAt(this._i++); return { done: false, value: val }; } else { return doneEnumerator; } }; function ArrayIterable(a) { this._a = a; } ArrayIterable.prototype[$iterator$] = function () { return new ArrayIterator(this._a); }; function ArrayIterator(a) { this._a = a; this._l = toLength(a); this._i = 0; } ArrayIterator.prototype[$iterator$] = function () { return this; }; ArrayIterator.prototype.next = function () { if (this._i < this._l) { var val = this._a[this._i++]; return { done: false, value: val }; } else { return doneEnumerator; } }; function numberIsFinite(value) { return typeof value === 'number' && root.isFinite(value); } function isNan(n) { return n !== n; } function getIterable(o) { var i = o[$iterator$], it; if (!i && typeof o === 'string') { it = new StringIterable(o); return it[$iterator$](); } if (!i && o.length !== undefined) { it = new ArrayIterable(o); return it[$iterator$](); } if (!i) { throw new TypeError('Object is not iterable'); } return o[$iterator$](); } function sign(value) { var number = +value; if (number === 0) { return number; } if (isNaN(number)) { return number; } return number < 0 ? -1 : 1; } function toLength(o) { var len = +o.length; if (isNaN(len)) { return 0; } if (len === 0 || !numberIsFinite(len)) { return len; } len = sign(len) * Math.floor(Math.abs(len)); if (len <= 0) { return 0; } if (len > maxSafeInteger) { return maxSafeInteger; } return len; } /** * This method creates a new Observable sequence from an array-like or iterable object. * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. * @param {Function} [mapFn] Map function to call on every element of the array. * @param {Any} [thisArg] The context to use calling the mapFn if provided. * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) { if (iterable == null) { throw new Error('iterable cannot be null.') } if (mapFn && !isFunction(mapFn)) { throw new Error('mapFn when provided must be a function'); } isScheduler(scheduler) || (scheduler = currentThreadScheduler); var list = Object(iterable), it = getIterable(list); return new AnonymousObservable(function (observer) { var i = 0; return scheduler.scheduleRecursive(function (self) { var next; try { next = it.next(); } catch (e) { observer.onError(e); return; } if (next.done) { observer.onCompleted(); return; } var result = next.value; if (mapFn && isFunction(mapFn)) { try { result = mapFn.call(thisArg, result, i); } catch (e) { observer.onError(e); return; } } observer.onNext(result); i++; self(); }); }); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * @deprecated use Observable.from or Observable.of * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { deprecate('fromArray', 'from'); isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0, len = array.length; return scheduler.scheduleRecursive(function (self) { if (count < len) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; function observableOf (scheduler, array) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0, len = array.length; return scheduler.scheduleRecursive(function (self) { if (count < len) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); } /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.of = function () { return observableOf(null, arguments); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.ofWithScheduler = function (scheduler) { return observableOf(scheduler, slice.call(arguments, 1)); }; /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.range(0, 10); * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleRecursiveWithState(0, function (i, self) { if (i < count) { observer.onNext(start + i); self(i + 1); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'just', and 'returnValue' for browsers <IE9. * * @example * var res = Rx.Observable.return(42); * var res = Rx.Observable.return(42, Rx.Scheduler.timeout); * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.just = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** @deprecated use return or just */ Observable.returnValue = function () { deprecate('returnValue', 'return or just'); return observableReturn.apply(null, arguments); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwError' for browsers <IE9. * @param {Mixed} exception An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwException = Observable.throwError = function (exception, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (observer) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) { var d, result; try { result = handler(exception); } catch (ex) { observer.onError(ex); return; } isPromise(result) && (result = observableFromPromise(result)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(observer)); }, observer.onCompleted.bind(observer))); return subscription; }, source); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchError = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * @deprecated use #catch or #catchError instead. */ observableProto.catchException = function (handlerOrSecond) { deprecate('catchException', 'catch or catchError'); return this.catchError(handlerOrSecond); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs. * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchError = Observable['catch'] = function () { return enumerableOf(argsOrArray(arguments, 0)).catchError(); }; /** * @deprecated use #catch or #catchError instead. */ Observable.catchException = function () { deprecate('catchException', 'catch or catchError'); return observableCatch.apply(null, arguments); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var args = slice.call(arguments); if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var args = slice.call(arguments), resultSelector = args.pop(); if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } } function done (i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }, this); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * * @example * 1 - concatenated = xs.concat(ys, zs); * 2 - concatenated = xs.concat([ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { var items = slice.call(arguments, 0); items.unshift(this); return observableConcat.apply(this, items); }; /** * Concatenates all the observable sequences. * @param {Array | Arguments} args Arguments or an array to concat to the observable sequence. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { return enumerableOf(argsOrArray(arguments, 0)).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatAll = function () { return this.merge(1); }; /** @deprecated Use `concatAll` instead. */ observableProto.concatObservable = function () { deprecate('concatObservable', 'concatAll'); return this.merge(1); }; /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); } var sources = this; return new AnonymousObservable(function (observer) { var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = []; function subscribe(xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); // Check for promises support isPromise(xs) && (xs = observableFromPromise(xs)); subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { group.remove(subscription); if (q.length > 0) { subscribe(q.shift()); } else { activeCount--; isStopped && activeCount === 0 && observer.onCompleted(); } })); } group.add(sources.subscribe(function (innerSource) { if (activeCount < maxConcurrentOrOther) { activeCount++; subscribe(innerSource); } else { q.push(innerSource); } }, observer.onError.bind(observer), function () { isStopped = true; activeCount === 0 && observer.onCompleted(); })); return group; }, sources); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources; if (!arguments[0]) { scheduler = immediateScheduler; sources = slice.call(arguments, 1); } else if (isScheduler(arguments[0])) { scheduler = arguments[0]; sources = slice.call(arguments, 1); } else { scheduler = immediateScheduler; sources = slice.call(arguments, 0); } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableOf(scheduler, sources).mergeAll(); }; /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeAll = function () { var sources = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(), isStopped = false, m = new SingleAssignmentDisposable(); group.add(m); m.setDisposable(sources.subscribe(function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check for promises support isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { group.remove(innerSubscription); isStopped && group.length === 1 && observer.onCompleted(); })); }, observer.onError.bind(observer), function () { isStopped = true; group.length === 1 && observer.onCompleted(); })); return group; }, sources); }; /** * @deprecated use #mergeAll instead. */ observableProto.mergeObservable = function () { deprecate('mergeObservable', 'mergeAll'); return this.mergeAll.apply(this, arguments); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && observer.onNext(left); }, observer.onError.bind(observer), function () { isOpen && observer.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, observer.onError.bind(observer), function () { rightSubscription.dispose(); })); return disposables; }, source); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe( function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); d.setDisposable(innerSource.subscribe( function (x) { latest === id && observer.onNext(x); }, function (e) { latest === id && observer.onError(e); }, function () { if (latest === id) { hasLatest = false; isStopped && observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; !hasLatest && observer.onCompleted(); }); return new CompositeDisposable(subscription, innerSubscription); }, sources); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(observer), other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) ); }, source); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { observer.onError(e); return; } observer.onNext(result); } else { observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }, first); } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); sources.unshift(parent); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = sources[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }, parent); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var args = slice.call(arguments, 0), first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } var compositeDisposable = new CompositeDisposable(subscriptions); compositeDisposable.add(disposableCreate(function () { for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { queues[qIdx] = []; } })); return compositeDisposable; }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { return new AnonymousObservable(this.subscribe.bind(this), this); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { return x.accept(observer); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }, this); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; keySelector || (keySelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var comparerEquals = false, key; try { key = keySelector(value); } catch (e) { observer.onError(e); return; } if (hasCurrentKey) { try { comparerEquals = comparer(currentKey, key); } catch (e) { observer.onError(e); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }, this); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.tap = function (observerOrOnNext, onError, onCompleted) { var source = this, onNextFunc; if (typeof observerOrOnNext === 'function') { onNextFunc = observerOrOnNext; } else { onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); onError = observerOrOnNext.onError.bind(observerOrOnNext); onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); } return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { onNextFunc(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (err) { if (onError) { try { onError(err); } catch (e) { observer.onError(e); } } observer.onError(err); }, function () { if (onCompleted) { try { onCompleted(); } catch (e) { observer.onError(e); } } observer.onCompleted(); }); }, this); }; /** @deprecated use #do or #tap instead. */ observableProto.doAction = function () { deprecate('doAction', 'do or tap'); return this.tap.apply(this, arguments); }; /** * Invokes an action for each element in the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onNext Action to invoke for each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) { return this.tap(arguments.length === 2 ? function (x) { onNext.call(thisArg, x); } : onNext); }; /** * Invokes an action upon exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onError Action to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) { return this.tap(noop, arguments.length === 2 ? function (e) { onError.call(thisArg, e); } : onError); }; /** * Invokes an action upon graceful termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) { return this.tap(noop, null, arguments.length === 2 ? function () { onCompleted.call(thisArg); } : onCompleted); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.ensure = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }, this); }; /** * @deprecated use #finally or #ensure instead. */ observableProto.finallyAction = function (action) { deprecate('finallyAction', 'finally or ensure'); return this.ensure(action); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }, source); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }, source); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * Note if you encounter an error and want it to retry once, then you must use .retry(2); * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(2); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchError(); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (observer) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { !hasValue && (hasValue = true); try { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { observer.onError(e); return; } observer.onNext(accumulation); }, observer.onError.bind(observer), function () { !hasValue && hasSeed && observer.onNext(seed); observer.onCompleted(); } ); }, source); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && observer.onNext(q.shift()); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }, source); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * @example * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * @param {Arguments} args The specified values to prepend to the observable sequence * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && isScheduler(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableOf([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence. * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, observer.onError.bind(observer), function () { while (q.length > 0) { observer.onNext(q.shift()); } observer.onCompleted(); }); }, source); }; function concatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i, source); isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).concatAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { if (isFunction(selector) && isFunction(resultSelector)) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }); } return isFunction(selector) ? concatMap(this, selector, thisArg) : concatMap(this, function () { return selector; }); }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.select = observableProto.map = function (selector, thisArg) { var selectorFn = isFunction(selector) ? selector : function () { return selector; }, source = this; return new AnonymousObservable(function (observer) { var count = 0; return source.subscribe(function (value) { var result; try { result = selectorFn.call(thisArg, value, count++, source); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }, source); }; /** * Retrieves the value of a specified property from all elements in the Observable sequence. * @param {String} prop The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (prop) { return this.map(function (x) { return x[prop]; }); }; function flatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i, source); isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).mergeAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { if (isFunction(selector) && isFunction(resultSelector)) { return this.flatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }, thisArg); } return isFunction(selector) ? flatMap(this, selector, thisArg) : flatMap(this, function () { return selector; }); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new Error(argumentOutOfRange); } var source = this; return new AnonymousObservable(function (observer) { var remaining = count; return source.subscribe(function (x) { if (remaining <= 0) { observer.onNext(x); } else { remaining--; } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }, source); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !predicate.call(thisArg, x, i++, source); } catch (e) { observer.onError(e); return; } } running && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }, source); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new RangeError(argumentOutOfRange); } if (count === 0) { return observableEmpty(scheduler); } var source = this; return new AnonymousObservable(function (observer) { var remaining = count; return source.subscribe(function (x) { if (remaining-- > 0) { observer.onNext(x); remaining === 0 && observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }, source); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var i = 0, running = true; return source.subscribe(function (x) { if (running) { try { running = predicate.call(thisArg, x, i++, source); } catch (e) { observer.onError(e); return; } if (running) { observer.onNext(x); } else { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }, source); }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * * @example * var res = source.where(function (value) { return value < 10; }); * var res = source.where(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.where = observableProto.filter = function (predicate, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var count = 0; return source.subscribe(function (value) { var shouldRun; try { shouldRun = predicate.call(thisArg, value, count++, parent); } catch (e) { observer.onError(e); return; } shouldRun && observer.onNext(value); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }, source); }; /** * Converts a callback function to an observable sequence. * * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. */ Observable.fromCallback = function (func, context, selector) { return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { function handler() { var results = arguments; if (selector) { try { results = selector(results); } catch (err) { observer.onError(err); return; } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; /** * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. * @param {Function} func The function to call * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. */ Observable.fromNodeCallback = function (func, context, selector) { return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { function handler(err) { if (err) { observer.onError(err); return; } var results = slice.call(arguments, 1); if (selector) { try { results = selector(results); } catch (e) { observer.onError(e); return; } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; function createListener (element, name, handler) { if (element.addEventListener) { element.addEventListener(name, handler, false); return disposableCreate(function () { element.removeEventListener(name, handler, false); }); } throw new Error('No listener found'); } function createEventListener (el, eventName, handler) { var disposables = new CompositeDisposable(); // Asume NodeList if (Object.prototype.toString.call(el) === '[object NodeList]') { for (var i = 0, len = el.length; i < len; i++) { disposables.add(createEventListener(el.item(i), eventName, handler)); } } else if (el) { disposables.add(createListener(el, eventName, handler)); } return disposables; } /** * Configuration option to determine whether to use native events only */ Rx.config.useNativeEvents = false; // Check for Angular/jQuery/Zepto support var jq = !!root.angular && !!angular.element ? angular.element : (!!root.jQuery ? root.jQuery : ( !!root.Zepto ? root.Zepto : null)); // Check for ember var ember = !!root.Ember && typeof root.Ember.addListener === 'function'; // Check for Backbone.Marionette. Note if using AMD add Marionette as a dependency of rxjs // for proper loading order! var marionette = !!root.Backbone && !!root.Backbone.Marionette; /** * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. * * @example * var source = Rx.Observable.fromEvent(element, 'mouseup'); * * @param {Object} element The DOMElement or NodeList to attach a listener. * @param {String} eventName The event name to attach the observable sequence. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence of events from the specified element and the specified event. */ Observable.fromEvent = function (element, eventName, selector) { // Node.js specific if (element.addListener) { return fromEventPattern( function (h) { element.addListener(eventName, h); }, function (h) { element.removeListener(eventName, h); }, selector); } // Use only if non-native events are allowed if (!Rx.config.useNativeEvents) { if (marionette) { return fromEventPattern( function (h) { element.on(eventName, h); }, function (h) { element.off(eventName, h); }, selector); } if (ember) { return fromEventPattern( function (h) { Ember.addListener(element, eventName, h); }, function (h) { Ember.removeListener(element, eventName, h); }, selector); } if (jq) { var $elem = jq(element); return fromEventPattern( function (h) { $elem.on(eventName, h); }, function (h) { $elem.off(eventName, h); }, selector); } } return new AnonymousObservable(function (observer) { return createEventListener( element, eventName, function handler (e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return } } observer.onNext(results); }); }).publish().refCount(); }; /** * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. * @param {Function} addHandler The function to add a handler to the emitter. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence which wraps an event from an event emitter */ var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) { return new AnonymousObservable(function (observer) { function innerHandler (e) { var result = e; if (selector) { try { result = selector(arguments); } catch (err) { observer.onError(err); return; } } observer.onNext(result); } var returnValue = addHandler(innerHandler); return disposableCreate(function () { if (removeHandler) { removeHandler(innerHandler, returnValue); } }); }).publish().refCount(); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return observableDefer(function () { var subject = new Rx.AsyncSubject(); promise.then( function (value) { subject.onNext(value); subject.onCompleted(); }, subject.onError.bind(subject)); return subject; }); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new TypeError('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, reject, function () { hasValue && resolve(value); }); }); }; /** * Invokes the asynchronous function, surfacing the result through an observable sequence. * @param {Function} functionAsync Asynchronous function which returns a Promise to run. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. */ Observable.startAsync = function (functionAsync) { var promise; try { promise = functionAsync(); } catch (e) { return observableThrow(e); } return observableFromPromise(promise); } /** * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. * * @example * 1 - res = source.multicast(observable); * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); * * @param {Function|Subject} subjectOrSubjectSelector * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. * Or: * Subject to push source elements into. * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.multicast = function (subjectOrSubjectSelector, selector) { var source = this; return typeof subjectOrSubjectSelector === 'function' ? new AnonymousObservable(function (observer) { var connectable = source.multicast(subjectOrSubjectSelector()); return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect()); }, source) : new ConnectableObservable(source, subjectOrSubjectSelector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of Multicast using a regular Subject. * * @example * var resres = source.publish(); * var res = source.publish(function (x) { return x; }); * * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publish = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new Subject(); }, selector) : this.multicast(new Subject()); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.share = function () { return this.publish().refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. * This operator is a specialization of Multicast using a AsyncSubject. * * @example * var res = source.publishLast(); * var res = source.publishLast(function (x) { return x; }); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishLast = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new AsyncSubject(); }, selector) : this.multicast(new AsyncSubject()); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. * This operator is a specialization of Multicast using a BehaviorSubject. * * @example * var res = source.publishValue(42); * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42); * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishValue = function (initialValueOrSelector, initialValue) { return arguments.length === 2 ? this.multicast(function () { return new BehaviorSubject(initialValue); }, initialValueOrSelector) : this.multicast(new BehaviorSubject(initialValueOrSelector)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareValue = function (initialValue) { return this.publishValue(initialValue).refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of Multicast using a ReplaySubject. * * @example * var res = source.replay(null, 3); * var res = source.replay(null, 3, 500); * var res = source.replay(null, 3, 500, scheduler); * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy. * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.replay = function (selector, bufferSize, window, scheduler) { return selector && isFunction(selector) ? this.multicast(function () { return new ReplaySubject(bufferSize, window, scheduler); }, selector) : this.multicast(new ReplaySubject(bufferSize, window, scheduler)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareReplay(3); * var res = source.shareReplay(3, 500); * var res = source.shareReplay(3, 500, scheduler); * * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareReplay = function (bufferSize, window, scheduler) { return this.replay(null, bufferSize, window, scheduler).refCount(); }; var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { inherits(ConnectableObservable, __super__); function ConnectableObservable(source, subject) { var hasSubscription = false, subscription, sourceObservable = source.asObservable(); this.connect = function () { if (!hasSubscription) { hasSubscription = true; subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () { hasSubscription = false; })); } return subscription; }; __super__.call(this, subject.subscribe.bind(subject)); } ConnectableObservable.prototype.refCount = function () { var connectableSubscription, count = 0, source = this; return new AnonymousObservable(function (observer) { var shouldConnect = ++count === 1, subscription = source.subscribe(observer); shouldConnect && (connectableSubscription = source.connect()); return function () { subscription.dispose(); --count === 0 && connectableSubscription.dispose(); }; }); }; return ConnectableObservable; }(Observable)); function observableTimerDate(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithAbsolute(dueTime, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerDateAndPeriod(dueTime, period, scheduler) { return new AnonymousObservable(function (observer) { var count = 0, d = dueTime, p = normalizeTime(period); return scheduler.scheduleRecursiveWithAbsolute(d, function (self) { if (p > 0) { var now = scheduler.now(); d = d + p; d <= now && (d = now + p); } observer.onNext(count++); self(d); }); }); } function observableTimerTimeSpan(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { return dueTime === period ? new AnonymousObservable(function (observer) { return scheduler.schedulePeriodicWithState(0, period, function (count) { observer.onNext(count); return count + 1; }); }) : observableDefer(function () { return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); }); } /** * Returns an observable sequence that produces a value after each period. * * @example * 1 - res = Rx.Observable.interval(1000); * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); * * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. * @returns {Observable} An observable sequence that produces a value after each period. */ var observableinterval = Observable.interval = function (period, scheduler) { return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler); }; /** * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. */ var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { var period; isScheduler(scheduler) || (scheduler = timeoutScheduler); if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { period = periodOrScheduler; } else if (isScheduler(periodOrScheduler)) { scheduler = periodOrScheduler; } if (dueTime instanceof Date && period === undefined) { return observableTimerDate(dueTime.getTime(), scheduler); } if (dueTime instanceof Date && period !== undefined) { period = periodOrScheduler; return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler); } return period === undefined ? observableTimerTimeSpan(dueTime, scheduler) : observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); }; function observableDelayTimeSpan(source, dueTime, scheduler) { return new AnonymousObservable(function (observer) { var active = false, cancelable = new SerialDisposable(), exception = null, q = [], running = false, subscription; subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { var d, shouldRun; if (notification.value.kind === 'E') { q = []; q.push(notification); exception = notification.value.exception; shouldRun = !running; } else { q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); shouldRun = !active; active = true; } if (shouldRun) { if (exception !== null) { observer.onError(exception); } else { d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { var e, recurseDueTime, result, shouldRecurse; if (exception !== null) { return; } running = true; do { result = null; if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { result = q.shift().value; } if (result !== null) { result.accept(observer); } } while (result !== null); shouldRecurse = false; recurseDueTime = 0; if (q.length > 0) { shouldRecurse = true; recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); } else { active = false; } e = exception; running = false; if (e !== null) { observer.onError(e); } else if (shouldRecurse) { self(recurseDueTime); } })); } } }); return new CompositeDisposable(subscription, cancelable); }, source); } function observableDelayDate(source, dueTime, scheduler) { return observableDefer(function () { return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler); }); } /** * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. * * @example * 1 - res = Rx.Observable.delay(new Date()); * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout); * * 3 - res = Rx.Observable.delay(5000); * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); * @memberOf Observable# * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delay = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return dueTime instanceof Date ? observableDelayDate(this, dueTime.getTime(), scheduler) : observableDelayTimeSpan(this, dueTime, scheduler); }; /** * Ignores values from an observable sequence which are followed by another value before dueTime. * @param {Number} dueTime Duration of the debounce period for each value (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the debounce timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The debounced sequence. */ observableProto.debounce = observableProto.throttleWithTimeout = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var cancelable = new SerialDisposable(), hasvalue = false, value, id = 0; var subscription = source.subscribe( function (x) { hasvalue = true; value = x; id++; var currentId = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleWithRelative(dueTime, function () { hasvalue && id === currentId && observer.onNext(value); hasvalue = false; })); }, function (e) { cancelable.dispose(); observer.onError(e); hasvalue = false; id++; }, function () { cancelable.dispose(); hasvalue && observer.onNext(value); observer.onCompleted(); hasvalue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }, this); }; /** * @deprecated use #debounce or #throttleWithTimeout instead. */ observableProto.throttle = function(dueTime, scheduler) { deprecate('throttle', 'debounce or throttleWithTimeout'); return this.debounce(dueTime, scheduler); }; /** * Records the timestamp for each value in an observable sequence. * * @example * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } * 2 - res = source.timestamp(Rx.Scheduler.timeout); * * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with timestamp information on values. */ observableProto.timestamp = function (scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return this.map(function (x) { return { value: x, timestamp: scheduler.now() }; }); }; function sampleObservable(source, sampler) { return new AnonymousObservable(function (observer) { var atEnd, value, hasValue; function sampleSubscribe() { if (hasValue) { hasValue = false; observer.onNext(value); } atEnd && observer.onCompleted(); } return new CompositeDisposable( source.subscribe(function (newValue) { hasValue = true; value = newValue; }, observer.onError.bind(observer), function () { atEnd = true; }), sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) ); }, source); } /** * Samples the observable sequence at each interval. * * @example * 1 - res = source.sample(sampleObservable); // Sampler tick sequence * 2 - res = source.sample(5000); // 5 seconds * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Sampled observable sequence. */ observableProto.sample = observableProto.throttleLatest = function (intervalOrSampler, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return typeof intervalOrSampler === 'number' ? sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) : sampleObservable(this, intervalOrSampler); }; /** * Returns the source observable sequence or the other observable sequence if dueTime elapses. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeout = function (dueTime, other, scheduler) { (other == null || typeof other === 'string') && (other = observableThrow(new Error(other || 'Timeout'))); isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = dueTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { var id = 0, original = new SingleAssignmentDisposable(), subscription = new SerialDisposable(), switched = false, timer = new SerialDisposable(); subscription.setDisposable(original); function createTimer() { var myId = id; timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { if (id === myId) { isPromise(other) && (other = observableFromPromise(other)); subscription.setDisposable(other.subscribe(observer)); } })); } createTimer(); original.setDisposable(source.subscribe(function (x) { if (!switched) { id++; observer.onNext(x); createTimer(); } }, function (e) { if (!switched) { id++; observer.onError(e); } }, function () { if (!switched) { id++; observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }, source); }; /** * Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration. * @param {Number} windowDuration time to wait before emitting another item after emitting the last item * @param {Scheduler} [scheduler] the Scheduler to use internally to manage the timers that handle timeout for each item. If not provided, defaults to Scheduler.timeout. * @returns {Observable} An Observable that performs the throttle operation. */ observableProto.throttleFirst = function (windowDuration, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var duration = +windowDuration || 0; if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); } var source = this; return new AnonymousObservable(function (observer) { var lastOnNext = 0; return source.subscribe( function (x) { var now = scheduler.now(); if (lastOnNext === 0 || now - lastOnNext >= duration) { lastOnNext = now; observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer) ); }, source); }; var PausableObservable = (function (__super__) { inherits(PausableObservable, __super__); function subscribe(observer) { var conn = this.source.publish(), subscription = conn.subscribe(observer), connection = disposableEmpty; var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) { if (b) { connection = conn.connect(); } else { connection.dispose(); connection = disposableEmpty; } }); return new CompositeDisposable(subscription, connection, pausable); } function PausableObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } __super__.call(this, subscribe, source); } PausableObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausable(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausable = function (pauser) { return new PausableObservable(this, pauser); }; function combineLatestSource(source, subject, resultSelector) { return new AnonymousObservable(function (observer) { var hasValue = [false, false], hasValueAll = false, isDone = false, values = new Array(2), err; function next(x, i) { values[i] = x var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { if (err) { observer.onError(err); return; } try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } if (isDone && values[1]) { observer.onCompleted(); } } return new CompositeDisposable( source.subscribe( function (x) { next(x, 0); }, function (e) { if (values[1]) { observer.onError(e); } else { err = e; } }, function () { isDone = true; values[1] && observer.onCompleted(); }), subject.subscribe( function (x) { next(x, 1); }, observer.onError.bind(observer), function () { isDone = true; next(true, 1); }) ); }, source); } var PausableBufferedObservable = (function (__super__) { inherits(PausableBufferedObservable, __super__); function subscribe(observer) { var q = [], previousShouldFire; var subscription = combineLatestSource( this.source, this.pauser.distinctUntilChanged().startWith(false), function (data, shouldFire) { return { data: data, shouldFire: shouldFire }; }) .subscribe( function (results) { if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) { previousShouldFire = results.shouldFire; // change in shouldFire if (results.shouldFire) { while (q.length > 0) { observer.onNext(q.shift()); } } } else { previousShouldFire = results.shouldFire; // new data if (results.shouldFire) { observer.onNext(results.data); } else { q.push(results.data); } } }, function (err) { // Empty buffer before sending error while (q.length > 0) { observer.onNext(q.shift()); } observer.onError(err); }, function () { // Empty buffer before sending completion while (q.length > 0) { observer.onNext(q.shift()); } observer.onCompleted(); } ); return subscription; } function PausableBufferedObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } __super__.call(this, subscribe, source); } PausableBufferedObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableBufferedObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableBufferedObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, * and yields the values that were buffered while paused. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausableBuffered(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausableBuffered = function (subject) { return new PausableBufferedObservable(this, subject); }; var ControlledObservable = (function (__super__) { inherits(ControlledObservable, __super__); function subscribe (observer) { return this.source.subscribe(observer); } function ControlledObservable (source, enableQueue) { __super__.call(this, subscribe, source); this.subject = new ControlledSubject(enableQueue); this.source = source.multicast(this.subject).refCount(); } ControlledObservable.prototype.request = function (numberOfItems) { if (numberOfItems == null) { numberOfItems = -1; } return this.subject.request(numberOfItems); }; return ControlledObservable; }(Observable)); var ControlledSubject = (function (__super__) { function subscribe (observer) { return this.subject.subscribe(observer); } inherits(ControlledSubject, __super__); function ControlledSubject(enableQueue) { enableQueue == null && (enableQueue = true); __super__.call(this, subscribe); this.subject = new Subject(); this.enableQueue = enableQueue; this.queue = enableQueue ? [] : null; this.requestedCount = 0; this.requestedDisposable = disposableEmpty; this.error = null; this.hasFailed = false; this.hasCompleted = false; this.controlledDisposable = disposableEmpty; } addProperties(ControlledSubject.prototype, Observer, { onCompleted: function () { this.hasCompleted = true; (!this.enableQueue || this.queue.length === 0) && this.subject.onCompleted(); }, onError: function (error) { this.hasFailed = true; this.error = error; (!this.enableQueue || this.queue.length === 0) && this.subject.onError(error); }, onNext: function (value) { var hasRequested = false; if (this.requestedCount === 0) { this.enableQueue && this.queue.push(value); } else { (this.requestedCount !== -1 && this.requestedCount-- === 0) && this.disposeCurrentRequest(); hasRequested = true; } hasRequested && this.subject.onNext(value); }, _processRequest: function (numberOfItems) { if (this.enableQueue) { while (this.queue.length >= numberOfItems && numberOfItems > 0) { this.subject.onNext(this.queue.shift()); numberOfItems--; } return this.queue.length !== 0 ? { numberOfItems: numberOfItems, returnValue: true } : { numberOfItems: numberOfItems, returnValue: false }; } if (this.hasFailed) { this.subject.onError(this.error); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } else if (this.hasCompleted) { this.subject.onCompleted(); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } return { numberOfItems: numberOfItems, returnValue: false }; }, request: function (number) { this.disposeCurrentRequest(); var self = this, r = this._processRequest(number); var number = r.numberOfItems; if (!r.returnValue) { this.requestedCount = number; this.requestedDisposable = disposableCreate(function () { self.requestedCount = 0; }); return this.requestedDisposable } else { return disposableEmpty; } }, disposeCurrentRequest: function () { this.requestedDisposable.dispose(); this.requestedDisposable = disposableEmpty; } }); return ControlledSubject; }(Observable)); /** * Attaches a controller to the observable sequence with the ability to queue. * @example * var source = Rx.Observable.interval(100).controlled(); * source.request(3); // Reads 3 values * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.controlled = function (enableQueue) { if (enableQueue == null) { enableQueue = true; } return new ControlledObservable(this, enableQueue); }; /** * Executes a transducer to transform the observable sequence * @param {Transducer} transducer A transducer to execute * @returns {Observable} An Observable sequence containing the results from the transducer. */ observableProto.transduce = function(transducer) { var source = this; function transformForObserver(observer) { return { init: function() { return observer; }, step: function(obs, input) { return obs.onNext(input); }, result: function(obs) { return obs.onCompleted(); } }; } return new AnonymousObservable(function(observer) { var xform = transducer(transformForObserver(observer)); return source.subscribe( function(v) { try { xform.step(observer, v); } catch (e) { observer.onError(e); } }, observer.onError.bind(observer), function() { xform.result(observer); } ); }, source); }; var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; } return typeof subscriber === 'function' ? disposableCreate(subscriber) : disposableEmpty; } function AnonymousObservable(subscribe, parent) { this.source = parent; if (!(this instanceof AnonymousObservable)) { return new AnonymousObservable(subscribe); } function s(observer) { var setDisposable = function () { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } }; var autoDetachObserver = new AutoDetachObserver(observer); if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(setDisposable); } else { setDisposable(); } return autoDetachObserver; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); var AutoDetachObserver = (function (__super__) { inherits(AutoDetachObserver, __super__); function AutoDetachObserver(observer) { __super__.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var noError = false; try { this.observer.onNext(value); noError = true; } catch (e) { throw e; } finally { !noError && this.dispose(); } }; AutoDetachObserverPrototype.error = function (err) { try { this.observer.onError(err); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.completed = function () { try { this.observer.onCompleted(); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); }; AutoDetachObserverPrototype.dispose = function () { __super__.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); /** @private */ var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; /** * @private * @memberOf InnerSubscription */ InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.exception) { observer.onError(this.exception); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, _super); /** * Creates a subject. * @constructor */ function Subject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; } addProperties(Subject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (__super__) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } var ex = this.exception, hv = this.hasValue, v = this.value; if (ex) { observer.onError(ex); } else if (hv) { observer.onNext(v); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, __super__); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { __super__.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.value = null; this.hasValue = false; this.observers = []; this.exception = null; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed.call(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var o, i, len; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var os = this.observers.slice(0), v = this.value, hv = this.hasValue; if (hv) { for (i = 0, len = os.length; i < len; i++) { o = os[i]; o.onNext(v); o.onCompleted(); } } else { for (i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } } this.observers = []; } }, /** * Notifies all subscribed observers about the error. * @param {Mixed} error The Error to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = error; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(error); } this.observers = []; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed.call(this); if (this.isStopped) { return; } this.value = value; this.hasValue = true; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { inherits(AnonymousSubject, __super__); function AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this, this.observable.subscribe.bind(this.observable)); } addProperties(AnonymousSubject.prototype, Observer, { onCompleted: function () { this.observer.onCompleted(); }, onError: function (exception) { this.observer.onError(exception); }, onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); /** * Represents a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); observer.onNext(this.value); return new InnerSubscription(this, observer); } var ex = this.exception; if (ex) { observer.onError(ex); } else { observer.onCompleted(); } return disposableEmpty; } inherits(BehaviorSubject, __super__); /** * @constructor * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. */ function BehaviorSubject(value) { __super__.call(this, subscribe); this.value = value, this.observers = [], this.isDisposed = false, this.isStopped = false, this.exception = null; } addProperties(BehaviorSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; this.exception = error; for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) { os[i].onError(error); } this.observers = []; }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (this.isStopped) { return; } this.value = value; for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) { os[i].onNext(value); } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.value = null; this.exception = null; } }); return BehaviorSubject; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. */ var ReplaySubject = Rx.ReplaySubject = (function (__super__) { function createRemovableDisposable(subject, observer) { return disposableCreate(function () { observer.dispose(); !subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1); }); } function subscribe(observer) { var so = new ScheduledObserver(this.scheduler, observer), subscription = createRemovableDisposable(this, so); checkDisposed.call(this); this._trim(this.scheduler.now()); this.observers.push(so); for (var i = 0, len = this.q.length; i < len; i++) { so.onNext(this.q[i].value); } if (this.hasError) { so.onError(this.error); } else if (this.isStopped) { so.onCompleted(); } so.ensureActive(); return subscription; } inherits(ReplaySubject, __super__); /** * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. * @param {Number} [bufferSize] Maximum element count of the replay buffer. * @param {Number} [windowSize] Maximum time length of the replay buffer. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. */ function ReplaySubject(bufferSize, windowSize, scheduler) { this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; this.scheduler = scheduler || currentThreadScheduler; this.q = []; this.observers = []; this.isStopped = false; this.isDisposed = false; this.hasError = false; this.error = null; __super__.call(this, subscribe); } addProperties(ReplaySubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, _trim: function (now) { while (this.q.length > this.bufferSize) { this.q.shift(); } while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { this.q.shift(); } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (this.isStopped) { return; } var now = this.scheduler.now(); this.q.push({ interval: now, value: value }); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { var observer = o[i]; observer.onNext(value); observer.ensureActive(); } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; this.error = error; this.hasError = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { var observer = o[i]; observer.onError(error); observer.ensureActive(); } this.observers = []; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { var observer = o[i]; observer.onCompleted(); observer.ensureActive(); } this.observers = []; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); return ReplaySubject; }(Observable)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } // All code before this point will be filtered from stack traces. var rEndingLine = captureLine(); }.call(this));
pkg/interface/soto/src/js/components/lib/icons/icon-spinner.js
ngzax/urbit
import React, { Component } from 'react'; export class Spinner extends Component { render() { let classes = !!this.props.classes ? this.props.classes : ""; let text = !!this.props.text ? this.props.text : ""; let awaiting = !!this.props.awaiting ? this.props.awaiting : false; if (awaiting) { return ( <div className={classes + " z-2 bg-white bg-gray0-d white-d"}> <img className="invert-d spin-active v-mid" src="/~dojo/img/Spinner.png" width={16} height={16} /> <p className="dib f9 ml2 v-mid inter">{text}</p> </div> ); } else { return null; } } }
static/node_modules/vue/src/platforms/web/runtime/modules/style.js
decaf-emu/huehuetenango
/* @flow */ import { getStyle, normalizeStyleBinding } from 'web/util/style' import { cached, camelize, extend, isDef, isUndef } from 'shared/util' const cssVarRE = /^--/ const importantRE = /\s*!important$/ const setProp = (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 { const 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 (let i = 0, len = val.length; i < len; i++) { el.style[normalizedName] = val[i] } } else { el.style[normalizedName] = val } } } const vendorNames = ['Webkit', 'Moz', 'ms'] let emptyStyle const normalize = cached(function (prop) { emptyStyle = emptyStyle || document.createElement('div').style prop = camelize(prop) if (prop !== 'filter' && (prop in emptyStyle)) { return prop } const capName = prop.charAt(0).toUpperCase() + prop.slice(1) for (let i = 0; i < vendorNames.length; i++) { const name = vendorNames[i] + capName if (name in emptyStyle) { return name } } }) function updateStyle (oldVnode: VNodeWithData, vnode: VNodeWithData) { const data = vnode.data const oldData = oldVnode.data if (isUndef(data.staticStyle) && isUndef(data.style) && isUndef(oldData.staticStyle) && isUndef(oldData.style) ) { return } let cur, name const el: any = vnode.elm const oldStaticStyle: any = oldData.staticStyle const oldStyleBinding: any = oldData.normalizedStyle || oldData.style || {} // if static style exists, stylebinding already merged into it when doing normalizeStyleData const oldStyle = oldStaticStyle || oldStyleBinding const 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 likley wants // to mutate it. vnode.data.normalizedStyle = isDef(style.__ob__) ? extend({}, style) : style const 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) } } } export default { create: updateStyle, update: updateStyle }
src/components/ListLoading/ListLoading.js
EricThsi/today-focus-news
import React, { Component } from 'react'; import './ListLoading.scss' class ListLoading extends Component { render() { return ( <div className="list_bottom"> <section> <a href="#"> Loading... </a> </section> </div> ); } } export default ListLoading;
app/containers/LocaleToggle/index.js
VonIobro/ab-web
/* * * LanguageToggle * */ import React from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import Toggle from 'components/Toggle'; import Wrapper from './Wrapper'; import messages from './messages'; import { appLocales } from '../../i18n'; import { changeLocale } from '../LanguageProvider/actions'; import { makeSelectLocale } from '../LanguageProvider/selectors'; export class LocaleToggle extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <Wrapper> <Toggle value={this.props.locale} values={appLocales} messages={messages} onToggle={this.props.onLocaleToggle} /> </Wrapper> ); } } LocaleToggle.propTypes = { onLocaleToggle: React.PropTypes.func, locale: React.PropTypes.string, }; const mapStateToProps = createSelector( makeSelectLocale(), (locale) => ({ locale }) ); export function mapDispatchToProps(dispatch) { return { onLocaleToggle: (evt) => dispatch(changeLocale(evt.target.value)), dispatch, }; } export default connect(mapStateToProps, mapDispatchToProps)(LocaleToggle);
src/components/login/LoginForm.js
yuri/notality
import React from 'react'; import { reduxForm } from 'redux-form'; import Form from '../ui/Form'; import FormGroup from '../ui/FormGroup'; import FormLabel from '../ui/FormLabel'; import FormError from '../ui/FormError'; import Input from '../ui/Input'; import Button from '../ui/Button'; import Alert from '../ui/Alert'; const validate = values => { const errors = {}; if (!values.username) { errors.username = 'Username is required.'; } if (!values.password) { errors.password = 'Password is required.'; } return errors; }; const LoginForm = (props) => { const { handleSubmit, resetForm, isPending, hasError, fields: { username, password, }, } = props; return ( <Form handleSubmit={ handleSubmit }> <Alert isVisible={ isPending }>Loading...</Alert> <Alert isVisible={ hasError } status="error">Invalid username and password</Alert> <FormGroup> <FormLabel>Username</FormLabel> <Input type="text" fieldDefinition={ username } /> <FormError isVisible={ username.touched && username.error }> { username.error } </FormError> </FormGroup> <FormGroup> <FormLabel>Password</FormLabel> <Input type="password" fieldDefinition={ password } /> <FormError isVisible={ password.touched && password.error }> { password.error } </FormError> </FormGroup> <FormGroup> <Button type="submit"> Login </Button> <Button onClick={ resetForm } type="button" className="ml2 bg-red"> Clear </Button> </FormGroup> </Form> ); }; export default reduxForm({ form: 'login', fields: [ 'username', 'password', ], validate, })(LoginForm);
ajax/libs/rsuite/0.0.5/suite.js
sashberd/cdnjs
/*! Last update: Mon Jun 06 2016 14:23:00 GMT+0800 (CST) */ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Suite=t():e.Suite=t()}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return e[r].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.PanelGroup=t.Panel=t.Content=t.Container=t.Table=t.Col=t.Row=t.Grid=t.Sidebar=t.Header=t.Text=t.RadioList=t.Radio=t.CheckboxList=t.Checkbox=t.HelpBlock=t.FormControl=t.ControlLabel=t.FormGroup=t.Form=t.Pagination=t.Breadcrumb=t.Navbar=t.Nav=t.Modal=t.Popover=t.Tooltip=t.Whisper=t.ButtonGroup=t.Dropdown=t.ButtonToolbar=t.Button=void 0;var o=n(1),a=r(o),i=n(167),u=r(i),s=n(168),l=r(s),c=n(169),p=r(c),d=n(176),f=r(d),h=n(191),v=r(h),m=n(192),y=r(m),g=n(193),b=r(g),_=n(201),E=r(_),N=n(204),O=r(N),C=n(210),P=r(C),w=n(212),T=r(w),x=n(214),D=r(x),M=n(215),k=r(M),S=n(216),R=r(S),I=n(217),j=r(I),A=n(218),V=r(A),L=n(219),U=r(L),F=n(220),B=r(F),W=n(221),H=r(W),K=n(222),q=r(K),z=n(223),Y=r(z),G=n(224),$=r(G),X=n(225),Q=r(X),Z=n(226),J=r(Z),ee=n(227),te=r(ee),ne=n(228),re=r(ne),oe=n(229),ae=r(oe),ie=n(230),ue=r(ie),se=n(231),le=r(se),ce=n(232),pe=r(ce),de=n(233),fe=r(de);t.Button=a["default"],t.ButtonToolbar=u["default"],t.Dropdown=l["default"],t.ButtonGroup=p["default"],t.Whisper=f["default"],t.Tooltip=v["default"],t.Popover=y["default"],t.Modal=b["default"],t.Nav=E["default"],t.Navbar=O["default"],t.Breadcrumb=P["default"],t.Pagination=T["default"],t.Form=D["default"],t.FormGroup=k["default"],t.ControlLabel=R["default"],t.FormControl=j["default"],t.HelpBlock=V["default"],t.Checkbox=U["default"],t.CheckboxList=B["default"],t.Radio=H["default"],t.RadioList=q["default"],t.Text=Y["default"],t.Header=$["default"],t.Sidebar=Q["default"],t.Grid=J["default"],t.Row=te["default"],t.Col=re["default"],t.Table=ae["default"],t.Container=ue["default"],t.Content=le["default"],t.Panel=pe["default"],t.PanelGroup=fe["default"],t.Table=ae["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=n(2),s=r(u),l=n(159),c=r(l),p=n(160),d=r(p),f=n(163),h=r(f),v=s["default"].createClass({displayName:"Button",mixins:[d["default"]],propTypes:{active:s["default"].PropTypes.bool,disabled:s["default"].PropTypes.bool,block:s["default"].PropTypes.bool,href:s["default"].PropTypes.string,target:s["default"].PropTypes.string,componentClass:s["default"].PropTypes.node,classPrefix:s["default"].PropTypes.string,type:s["default"].PropTypes.oneOf(["button","reset","submit"])},getDefaultProps:function(){return{classPrefix:"btn",active:!1,type:"button",disabled:!1,block:!1}},renderAnchor:function(e){var t=this.props.componentClass||h["default"],n=this.props.href||"#";return s["default"].createElement(t,i({},this.props,{href:n,className:e,role:"button"}),this.props.children)},renderButton:function(e){var t=this.props.componentClass||"button";return s["default"].createElement(t,i({},this.props,{className:e}),this.props.children)},render:function(){var e=c["default"].apply(void 0,[o({btn:!0,active:this.props.active,disabled:this.props.disabled},this.prefix("block"),this.props.block)].concat(a(this.getClassNames()),[this.props.className])),t=this.props.href||this.props.target?"renderAnchor":"renderButton";return this[t](e)}});t["default"]=v},function(e,t,n){"use strict";e.exports=n(3)},function(e,t,n){"use strict";var r=n(4),o=n(149),a=n(153),i=n(40),u=n(158),s={};i(s,a),i(s,{findDOMNode:u("findDOMNode","ReactDOM","react-dom",r,r.findDOMNode),render:u("render","ReactDOM","react-dom",r,r.render),unmountComponentAtNode:u("unmountComponentAtNode","ReactDOM","react-dom",r,r.unmountComponentAtNode),renderToString:u("renderToString","ReactDOMServer","react-dom/server",o,o.renderToString),renderToStaticMarkup:u("renderToStaticMarkup","ReactDOMServer","react-dom/server",o,o.renderToStaticMarkup)}),s.__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=r,s.__SECRET_DOM_SERVER_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=o,e.exports=s},function(e,t,n){(function(t){"use strict";var r=n(6),o=n(7),a=n(72),i=n(46),u=n(29),s=n(19),l=n(51),c=n(55),p=n(147),d=n(92),f=n(148),h=n(26);a.inject();var v=s.measure("React","render",u.render),m={findDOMNode:d,render:v,unmountComponentAtNode:u.unmountComponentAtNode,version:p,unstable_batchedUpdates:c.batchedUpdates,unstable_renderSubtreeIntoContainer:f};if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject&&__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({CurrentOwner:r,InstanceHandles:i,Mount:u,Reconciler:l,TextComponent:o}),"production"!==t.env.NODE_ENV){var y=n(10);if(y.canUseDOM&&window.top===window.self){"undefined"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&(navigator.userAgent.indexOf("Chrome")>-1&&-1===navigator.userAgent.indexOf("Edge")||navigator.userAgent.indexOf("Firefox")>-1)&&console.debug("Download the React DevTools for a better development experience: https://fb.me/react-devtools");var g=document.documentMode&&document.documentMode<8;"production"!==t.env.NODE_ENV?h(!g,'Internet Explorer is running in compatibility mode; please add the following tag to your HTML to prevent this from happening: <meta http-equiv="X-UA-Compatible" content="IE=edge" />'):void 0;for(var b=[Array.isArray,Array.prototype.every,Array.prototype.forEach,Array.prototype.indexOf,Array.prototype.map,Date.now,Function.prototype.bind,Object.keys,String.prototype.split,String.prototype.trim,Object.create,Object.freeze],_=0;_<b.length;_++)if(!b[_]){console.error("One or more ES5 shim/shams expected by React are not available: https://fb.me/react-warning-polyfills");break}}}e.exports=m}).call(t,n(5))},function(e,t){function n(){l=!1,i.length?s=i.concat(s):c=-1,s.length&&r()}function r(){if(!l){var e=setTimeout(n);l=!0;for(var t=s.length;t;){for(i=s,s=[];++c<t;)i&&i[c].run();c=-1,t=s.length}i=null,l=!1,clearTimeout(e)}}function o(e,t){this.fun=e,this.array=t}function a(){}var i,u=e.exports={},s=[],l=!1,c=-1;u.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];s.push(new o(e,t)),1!==s.length||l||setTimeout(r,0)},o.prototype.run=function(){this.fun.apply(null,this.array)},u.title="browser",u.browser=!0,u.env={},u.argv=[],u.version="",u.versions={},u.on=a,u.addListener=a,u.once=a,u.off=a,u.removeListener=a,u.removeAllListeners=a,u.emit=a,u.binding=function(e){throw new Error("process.binding is not supported")},u.cwd=function(){return"/"},u.chdir=function(e){throw new Error("process.chdir is not supported")},u.umask=function(){return 0}},function(e,t){"use strict";var n={current:null};e.exports=n},function(e,t,n){(function(t){"use strict";var r=n(8),o=n(23),a=n(27),i=n(29),u=n(40),s=n(22),l=n(21),c=n(71),p=function(e){};u(p.prototype,{construct:function(e){this._currentElement=e,this._stringText=""+e,this._rootNodeID=null,this._mountIndex=0},mountComponent:function(e,n,r){if("production"!==t.env.NODE_ENV&&r[c.ancestorInfoContextKey]&&c("span",null,r[c.ancestorInfoContextKey]),this._rootNodeID=e,n.useCreateElement){var a=r[i.ownerDocumentContextKey],u=a.createElement("span");return o.setAttributeForID(u,e),i.getID(u),l(u,this._stringText),u}var p=s(this._stringText);return n.renderToStaticMarkup?p:"<span "+o.createMarkupForID(e)+">"+p+"</span>"},receiveComponent:function(e,t){if(e!==this._currentElement){this._currentElement=e;var n=""+e;if(n!==this._stringText){this._stringText=n;var o=i.getNode(this._rootNodeID);r.updateTextContent(o,n)}}},unmountComponent:function(){a.unmountIDFromEnvironment(this._rootNodeID)}}),e.exports=p}).call(t,n(5))},function(e,t,n){(function(t){"use strict";function r(e,t,n){var r=n>=e.childNodes.length?null:e.childNodes.item(n);e.insertBefore(t,r)}var o=n(9),a=n(17),i=n(19),u=n(20),s=n(21),l=n(14),c={dangerouslyReplaceNodeWithMarkup:o.dangerouslyReplaceNodeWithMarkup,updateTextContent:s,processUpdates:function(e,n){for(var i,c=null,p=null,d=0;d<e.length;d++)if(i=e[d],i.type===a.MOVE_EXISTING||i.type===a.REMOVE_NODE){var f=i.fromIndex,h=i.parentNode.childNodes[f],v=i.parentID;h?void 0:"production"!==t.env.NODE_ENV?l(!1,"processUpdates(): Unable to find child %s of element. This probably means the DOM was unexpectedly mutated (e.g., by the browser), usually due to forgetting a <tbody> when using tables, nesting tags like <form>, <p>, or <a>, or using non-SVG elements in an <svg> parent. Try inspecting the child nodes of the element with React ID `%s`.",f,v):l(!1),c=c||{},c[v]=c[v]||[],c[v][f]=h,p=p||[],p.push(h)}var m;if(m=n.length&&"string"==typeof n[0]?o.dangerouslyRenderMarkup(n):n,p)for(var y=0;y<p.length;y++)p[y].parentNode.removeChild(p[y]);for(var g=0;g<e.length;g++)switch(i=e[g],i.type){case a.INSERT_MARKUP:r(i.parentNode,m[i.markupIndex],i.toIndex);break;case a.MOVE_EXISTING:r(i.parentNode,c[i.parentID][i.fromIndex],i.toIndex);break;case a.SET_MARKUP:u(i.parentNode,i.content);break;case a.TEXT_CONTENT:s(i.parentNode,i.content);break;case a.REMOVE_NODE:}}};i.measureMethods(c,"DOMChildrenOperations",{updateTextContent:"updateTextContent"}),e.exports=c}).call(t,n(5))},function(e,t,n){(function(t){"use strict";function r(e){return e.substring(1,e.indexOf(" "))}var o=n(10),a=n(11),i=n(16),u=n(15),s=n(14),l=/^(<[^ \/>]+)/,c="data-danger-index",p={dangerouslyRenderMarkup:function(e){o.canUseDOM?void 0:"production"!==t.env.NODE_ENV?s(!1,"dangerouslyRenderMarkup(...): Cannot render markup in a worker thread. Make sure `window` and `document` are available globally before requiring React when unit testing or use ReactDOMServer.renderToString for server rendering."):s(!1);for(var n,p={},d=0;d<e.length;d++)e[d]?void 0:"production"!==t.env.NODE_ENV?s(!1,"dangerouslyRenderMarkup(...): Missing markup."):s(!1),n=r(e[d]),n=u(n)?n:"*",p[n]=p[n]||[],p[n][d]=e[d];var f=[],h=0;for(n in p)if(p.hasOwnProperty(n)){var v,m=p[n];for(v in m)if(m.hasOwnProperty(v)){var y=m[v];m[v]=y.replace(l,"$1 "+c+'="'+v+'" ')}for(var g=a(m.join(""),i),b=0;b<g.length;++b){var _=g[b];_.hasAttribute&&_.hasAttribute(c)?(v=+_.getAttribute(c),_.removeAttribute(c),f.hasOwnProperty(v)?"production"!==t.env.NODE_ENV?s(!1,"Danger: Assigning to an already-occupied result index."):s(!1):void 0,f[v]=_,h+=1):"production"!==t.env.NODE_ENV&&console.error("Danger: Discarding unexpected node:",_)}}return h!==f.length?"production"!==t.env.NODE_ENV?s(!1,"Danger: Did not assign to every index of resultList."):s(!1):void 0,f.length!==e.length?"production"!==t.env.NODE_ENV?s(!1,"Danger: Expected markup to render %s nodes, but rendered %s.",e.length,f.length):s(!1):void 0,f},dangerouslyReplaceNodeWithMarkup:function(e,n){o.canUseDOM?void 0:"production"!==t.env.NODE_ENV?s(!1,"dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a worker thread. Make sure `window` and `document` are available globally before requiring React when unit testing or use ReactDOMServer.renderToString() for server rendering."):s(!1),n?void 0:"production"!==t.env.NODE_ENV?s(!1,"dangerouslyReplaceNodeWithMarkup(...): Missing markup."):s(!1),"html"===e.tagName.toLowerCase()?"production"!==t.env.NODE_ENV?s(!1,"dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the <html> node. This is because browser quirks make this unreliable and/or slow. If you want to render to the root you must use server rendering. See ReactDOMServer.renderToString()."):s(!1):void 0;var r;r="string"==typeof n?a(n,i)[0]:n,e.parentNode.replaceChild(r,e)}};e.exports=p}).call(t,n(5))},function(e,t){"use strict";var n=!("undefined"==typeof window||!window.document||!window.document.createElement),r={canUseDOM:n,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:n&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:n&&!!window.screen,isInWorker:!n};e.exports=r},function(e,t,n){(function(t){"use strict";function r(e){var t=e.match(c);return t&&t[1].toLowerCase()}function o(e,n){var o=l;l?void 0:"production"!==t.env.NODE_ENV?s(!1,"createNodesFromMarkup dummy not initialized"):s(!1);var a=r(e),c=a&&u(a);if(c){o.innerHTML=c[1]+e+c[2];for(var p=c[0];p--;)o=o.lastChild}else o.innerHTML=e;var d=o.getElementsByTagName("script");d.length&&(n?void 0:"production"!==t.env.NODE_ENV?s(!1,"createNodesFromMarkup(...): Unexpected <script> element rendered."):s(!1),i(d).forEach(n));for(var f=i(o.childNodes);o.lastChild;)o.removeChild(o.lastChild);return f}var a=n(10),i=n(12),u=n(15),s=n(14),l=a.canUseDOM?document.createElement("div"):null,c=/^\s*<(\w+)/;e.exports=o}).call(t,n(5))},function(e,t,n){"use strict";function r(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 r(e)?Array.isArray(e)?e.slice():a(e):[e]}var a=n(13);e.exports=o},function(e,t,n){(function(t){"use strict";function r(e){var n=e.length;if(Array.isArray(e)||"object"!=typeof e&&"function"!=typeof e?"production"!==t.env.NODE_ENV?o(!1,"toArray: Array-like object expected"):o(!1):void 0,"number"!=typeof n?"production"!==t.env.NODE_ENV?o(!1,"toArray: Object needs a length property"):o(!1):void 0,0===n||n-1 in e?void 0:"production"!==t.env.NODE_ENV?o(!1,"toArray: Object should have keys for indices"):o(!1),e.hasOwnProperty)try{return Array.prototype.slice.call(e)}catch(r){}for(var a=Array(n),i=0;n>i;i++)a[i]=e[i];return a}var o=n(14);e.exports=r}).call(t,n(5))},function(e,t,n){(function(t){"use strict";function n(e,n,r,o,a,i,u,s){if("production"!==t.env.NODE_ENV&&void 0===n)throw new Error("invariant requires an error message argument");if(!e){var l;if(void 0===n)l=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[r,o,a,i,u,s],p=0;l=new Error(n.replace(/%s/g,function(){return c[p++]})),l.name="Invariant Violation"}throw l.framesToPop=1,l}}e.exports=n}).call(t,n(5))},function(e,t,n){(function(t){"use strict";function r(e){return i?void 0:"production"!==t.env.NODE_ENV?a(!1,"Markup wrapping node not initialized"):a(!1),d.hasOwnProperty(e)||(e="*"),u.hasOwnProperty(e)||("*"===e?i.innerHTML="<link />":i.innerHTML="<"+e+"></"+e+">",u[e]=!i.firstChild),u[e]?d[e]:null}var o=n(10),a=n(14),i=o.canUseDOM?document.createElement("div"):null,u={},s=[1,'<select multiple="true">',"</select>"],l=[1,"<table>","</table>"],c=[3,"<table><tbody><tr>","</tr></tbody></table>"],p=[1,'<svg xmlns="http://www.w3.org/2000/svg">',"</svg>"],d={"*":[1,"?<div>","</div>"],area:[1,"<map>","</map>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],legend:[1,"<fieldset>","</fieldset>"],param:[1,"<object>","</object>"],tr:[2,"<table><tbody>","</tbody></table>"],optgroup:s,option:s,caption:l,colgroup:l,tbody:l,tfoot:l,thead:l,td:c,th:c},f=["circle","clipPath","defs","ellipse","g","image","line","linearGradient","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","text","tspan"];f.forEach(function(e){d[e]=p,u[e]=!0}),e.exports=r}).call(t,n(5))},function(e,t){"use strict";function n(e){return function(){return e}}function r(){}r.thatReturns=n,r.thatReturnsFalse=n(!1),r.thatReturnsTrue=n(!0),r.thatReturnsNull=n(null),r.thatReturnsThis=function(){return this},r.thatReturnsArgument=function(e){return e},e.exports=r},function(e,t,n){"use strict";var r=n(18),o=r({INSERT_MARKUP:null,MOVE_EXISTING:null,REMOVE_NODE:null,SET_MARKUP:null,TEXT_CONTENT:null});e.exports=o},function(e,t,n){(function(t){"use strict";var r=n(14),o=function(e){var n,o={};e instanceof Object&&!Array.isArray(e)?void 0:"production"!==t.env.NODE_ENV?r(!1,"keyMirror(...): Argument must be an object."):r(!1);for(n in e)e.hasOwnProperty(n)&&(o[n]=n);return o};e.exports=o}).call(t,n(5))},function(e,t,n){(function(t){"use strict";function n(e,t,n){return n}var r={enableMeasure:!1,storedMeasure:n,measureMethods:function(e,n,o){if("production"!==t.env.NODE_ENV)for(var a in o)o.hasOwnProperty(a)&&(e[a]=r.measure(n,o[a],e[a]))},measure:function(e,n,o){if("production"!==t.env.NODE_ENV){var a=null,i=function(){return r.enableMeasure?(a||(a=r.storedMeasure(e,n,o)),a.apply(this,arguments)):o.apply(this,arguments)};return i.displayName=e+"_"+n,i}return o},injection:{injectMeasure:function(e){r.storedMeasure=e}}};e.exports=r}).call(t,n(5))},function(e,t,n){"use strict";var r=n(10),o=/^[ \r\n\t\f]/,a=/<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/,i=function(e,t){e.innerHTML=t};if("undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction&&(i=function(e,t){MSApp.execUnsafeLocalFunction(function(){e.innerHTML=t})}),r.canUseDOM){var u=document.createElement("div");u.innerHTML=" ",""===u.innerHTML&&(i=function(e,t){if(e.parentNode&&e.parentNode.replaceChild(e,e),o.test(t)||"<"===t[0]&&a.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})}e.exports=i},function(e,t,n){"use strict";var r=n(10),o=n(22),a=n(20),i=function(e,t){e.textContent=t};r.canUseDOM&&("textContent"in document.documentElement||(i=function(e,t){a(e,o(t))})),e.exports=i},function(e,t){"use strict";function n(e){return o[e]}function r(e){return(""+e).replace(a,n)}var o={"&":"&amp;",">":"&gt;","<":"&lt;",'"':"&quot;","'":"&#x27;"},a=/[&><"']/g;e.exports=r},function(e,t,n){(function(t){"use strict";function r(e){return p.hasOwnProperty(e)?!0:c.hasOwnProperty(e)?!1:l.test(e)?(p[e]=!0,!0):(c[e]=!0,"production"!==t.env.NODE_ENV?s(!1,"Invalid attribute name: `%s`",e):void 0,!1)}function o(e,t){return null==t||e.hasBooleanValue&&!t||e.hasNumericValue&&isNaN(t)||e.hasPositiveNumericValue&&1>t||e.hasOverloadedBooleanValue&&t===!1}var a=n(24),i=n(19),u=n(25),s=n(26),l=/^[a-zA-Z_][\w\.\-]*$/,c={},p={};if("production"!==t.env.NODE_ENV)var d={children:!0,dangerouslySetInnerHTML:!0,key:!0,ref:!0},f={},h=function(e){if(!(d.hasOwnProperty(e)&&d[e]||f.hasOwnProperty(e)&&f[e])){f[e]=!0;var n=e.toLowerCase(),r=a.isCustomAttribute(n)?n:a.getPossibleStandardName.hasOwnProperty(n)?a.getPossibleStandardName[n]:null;"production"!==t.env.NODE_ENV?s(null==r,"Unknown DOM property %s. Did you mean %s?",e,r):void 0}};var v={createMarkupForID:function(e){return a.ID_ATTRIBUTE_NAME+"="+u(e)},setAttributeForID:function(e,t){e.setAttribute(a.ID_ATTRIBUTE_NAME,t)},createMarkupForProperty:function(e,n){var r=a.properties.hasOwnProperty(e)?a.properties[e]:null;if(r){if(o(r,n))return"";var i=r.attributeName;return r.hasBooleanValue||r.hasOverloadedBooleanValue&&n===!0?i+'=""':i+"="+u(n)}return a.isCustomAttribute(e)?null==n?"":e+"="+u(n):("production"!==t.env.NODE_ENV&&h(e),null)},createMarkupForCustomAttribute:function(e,t){return r(e)&&null!=t?e+"="+u(t):""},setValueForProperty:function(e,n,r){var i=a.properties.hasOwnProperty(n)?a.properties[n]:null;if(i){var u=i.mutationMethod;if(u)u(e,r);else if(o(i,r))this.deleteValueForProperty(e,n);else if(i.mustUseAttribute){var s=i.attributeName,l=i.attributeNamespace;l?e.setAttributeNS(l,s,""+r):i.hasBooleanValue||i.hasOverloadedBooleanValue&&r===!0?e.setAttribute(s,""):e.setAttribute(s,""+r)}else{var c=i.propertyName;i.hasSideEffects&&""+e[c]==""+r||(e[c]=r)}}else a.isCustomAttribute(n)?v.setValueForAttribute(e,n,r):"production"!==t.env.NODE_ENV&&h(n)},setValueForAttribute:function(e,t,n){r(t)&&(null==n?e.removeAttribute(t):e.setAttribute(t,""+n))},deleteValueForProperty:function(e,n){var r=a.properties.hasOwnProperty(n)?a.properties[n]:null;if(r){var o=r.mutationMethod;if(o)o(e,void 0);else if(r.mustUseAttribute)e.removeAttribute(r.attributeName);else{var i=r.propertyName,u=a.getDefaultValueForProperty(e.nodeName,i);r.hasSideEffects&&""+e[i]===u||(e[i]=u)}}else a.isCustomAttribute(n)?e.removeAttribute(n):"production"!==t.env.NODE_ENV&&h(n)}};i.measureMethods(v,"DOMPropertyOperations",{setValueForProperty:"setValueForProperty",setValueForAttribute:"setValueForAttribute",deleteValueForProperty:"deleteValueForProperty"}),e.exports=v}).call(t,n(5))},function(e,t,n){(function(t){"use strict";function r(e,t){return(e&t)===t}var o=n(14),a={MUST_USE_ATTRIBUTE:1,MUST_USE_PROPERTY:2,HAS_SIDE_EFFECTS:4,HAS_BOOLEAN_VALUE:8,HAS_NUMERIC_VALUE:16,HAS_POSITIVE_NUMERIC_VALUE:48,HAS_OVERLOADED_BOOLEAN_VALUE:64,injectDOMPropertyConfig:function(e){var n=a,i=e.Properties||{},s=e.DOMAttributeNamespaces||{},l=e.DOMAttributeNames||{},c=e.DOMPropertyNames||{},p=e.DOMMutationMethods||{};e.isCustomAttribute&&u._isCustomAttributeFunctions.push(e.isCustomAttribute);for(var d in i){u.properties.hasOwnProperty(d)?"production"!==t.env.NODE_ENV?o(!1,"injectDOMPropertyConfig(...): You're trying to inject DOM property '%s' which has already been injected. You may be accidentally injecting the same DOM property config twice, or you may be injecting two configs that have conflicting property names.",d):o(!1):void 0;var f=d.toLowerCase(),h=i[d],v={attributeName:f,attributeNamespace:null,propertyName:d,mutationMethod:null,mustUseAttribute:r(h,n.MUST_USE_ATTRIBUTE),mustUseProperty:r(h,n.MUST_USE_PROPERTY),hasSideEffects:r(h,n.HAS_SIDE_EFFECTS),hasBooleanValue:r(h,n.HAS_BOOLEAN_VALUE),hasNumericValue:r(h,n.HAS_NUMERIC_VALUE),hasPositiveNumericValue:r(h,n.HAS_POSITIVE_NUMERIC_VALUE),hasOverloadedBooleanValue:r(h,n.HAS_OVERLOADED_BOOLEAN_VALUE)};if(v.mustUseAttribute&&v.mustUseProperty?"production"!==t.env.NODE_ENV?o(!1,"DOMProperty: Cannot require using both attribute and property: %s",d):o(!1):void 0,!v.mustUseProperty&&v.hasSideEffects?"production"!==t.env.NODE_ENV?o(!1,"DOMProperty: Properties that have side effects must use property: %s",d):o(!1):void 0,v.hasBooleanValue+v.hasNumericValue+v.hasOverloadedBooleanValue<=1?void 0:"production"!==t.env.NODE_ENV?o(!1,"DOMProperty: Value can be one of boolean, overloaded boolean, or numeric value, but not a combination: %s",d):o(!1),"production"!==t.env.NODE_ENV&&(u.getPossibleStandardName[f]=d),l.hasOwnProperty(d)){var m=l[d];v.attributeName=m,"production"!==t.env.NODE_ENV&&(u.getPossibleStandardName[m]=d)}s.hasOwnProperty(d)&&(v.attributeNamespace=s[d]),c.hasOwnProperty(d)&&(v.propertyName=c[d]),p.hasOwnProperty(d)&&(v.mutationMethod=p[d]),u.properties[d]=v}}},i={},u={ID_ATTRIBUTE_NAME:"data-reactid",properties:{},getPossibleStandardName:"production"!==t.env.NODE_ENV?{}:null,_isCustomAttributeFunctions:[],isCustomAttribute:function(e){for(var t=0;t<u._isCustomAttributeFunctions.length;t++){var n=u._isCustomAttributeFunctions[t];if(n(e))return!0}return!1},getDefaultValueForProperty:function(e,t){var n,r=i[e];return r||(i[e]=r={}),t in r||(n=document.createElement(e),r[t]=n[t]),r[t]},injection:a};e.exports=u}).call(t,n(5))},function(e,t,n){"use strict";function r(e){return'"'+o(e)+'"'}var o=n(22);e.exports=r},function(e,t,n){(function(t){"use strict";var r=n(16),o=r;"production"!==t.env.NODE_ENV&&(o=function(e,t){for(var n=arguments.length,r=Array(n>2?n-2:0),o=2;n>o;o++)r[o-2]=arguments[o];if(void 0===t)throw new Error("`warning(condition, format, ...args)` requires a warning message argument");if(0!==t.indexOf("Failed Composite propType: ")&&!e){var a=0,i="Warning: "+t.replace(/%s/g,function(){return r[a++]});"undefined"!=typeof console&&console.error(i);try{throw new Error(i)}catch(u){}}}),e.exports=o}).call(t,n(5))},function(e,t,n){"use strict";var r=n(28),o=n(29),a={processChildrenUpdates:r.dangerouslyProcessChildrenUpdates,replaceNodeWithMarkupByID:r.dangerouslyReplaceNodeWithMarkupByID,unmountIDFromEnvironment:function(e){o.purgeID(e)}};e.exports=a},function(e,t,n){(function(t){"use strict";var r=n(8),o=n(23),a=n(29),i=n(19),u=n(14),s={dangerouslySetInnerHTML:"`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.",style:"`style` must be set using `updateStylesByID()`."},l={updatePropertyByID:function(e,n,r){var i=a.getNode(e);s.hasOwnProperty(n)?"production"!==t.env.NODE_ENV?u(!1,"updatePropertyByID(...): %s",s[n]):u(!1):void 0,null!=r?o.setValueForProperty(i,n,r):o.deleteValueForProperty(i,n)},dangerouslyReplaceNodeWithMarkupByID:function(e,t){var n=a.getNode(e);r.dangerouslyReplaceNodeWithMarkup(n,t)},dangerouslyProcessChildrenUpdates:function(e,t){for(var n=0;n<e.length;n++)e[n].parentNode=a.getNode(e[n].parentID);r.processUpdates(e,t)}};i.measureMethods(l,"ReactDOMIDOperations",{dangerouslyReplaceNodeWithMarkupByID:"dangerouslyReplaceNodeWithMarkupByID",dangerouslyProcessChildrenUpdates:"dangerouslyProcessChildrenUpdates"}),e.exports=l}).call(t,n(5))},function(e,t,n){(function(t){"use strict";function r(e,t){for(var n=Math.min(e.length,t.length),r=0;n>r;r++)if(e.charAt(r)!==t.charAt(r))return r;return e.length===t.length?-1:n}function o(e){return e?e.nodeType===q?e.documentElement:e.firstChild:null}function a(e){var t=o(e);return t&&ee.getID(t)}function i(e){var n=u(e);if(n)if(H.hasOwnProperty(n)){var r=H[n];r!==e&&(p(r,n)?"production"!==t.env.NODE_ENV?V(!1,"ReactMount: Two valid but unequal nodes with the same `%s`: %s",W,n):V(!1):void 0,H[n]=e)}else H[n]=e;return n}function u(e){return e&&e.getAttribute&&e.getAttribute(W)||""}function s(e,t){var n=u(e);n!==t&&delete H[n],e.setAttribute(W,t),H[t]=e}function l(e){return H.hasOwnProperty(e)&&p(H[e],e)||(H[e]=ee.findReactNodeByID(e)),H[e]}function c(e){var t=T.get(e)._rootNodeID;return P.isNullComponentID(t)?null:(H.hasOwnProperty(t)&&p(H[t],t)||(H[t]=ee.findReactNodeByID(t)),H[t])}function p(e,n){if(e){u(e)!==n?"production"!==t.env.NODE_ENV?V(!1,"ReactMount: Unexpected modification of `%s`",W):V(!1):void 0;var r=ee.findReactContainerForID(n);if(r&&j(r,e))return!0}return!1}function d(e){delete H[e]}function f(e){var t=H[e];return t&&p(t,e)?void(Z=t):!1}function h(e){Z=null,w.traverseAncestors(e,f);var t=Z;return Z=null,t}function v(e,n,r,o,a,i){if(O.useCreateElement&&(i=R({},i),r.nodeType===q?i[Y]=r:i[Y]=r.ownerDocument),"production"!==t.env.NODE_ENV){i===I&&(i={});var u=r.nodeName.toLowerCase();i[F.ancestorInfoContextKey]=F.updatedAncestorInfo(null,u,null)}var s=M.mountComponent(e,n,o,i);e._renderedComponent._topLevelWrapper=e,ee._mountImageIntoNode(s,r,a,o)}function m(e,t,n,r,o){var a=S.ReactReconcileTransaction.getPooled(r);a.perform(v,null,e,t,n,a,r,o),S.ReactReconcileTransaction.release(a)}function y(e,t){for(M.unmountComponent(e),t.nodeType===q&&(t=t.documentElement);t.lastChild;)t.removeChild(t.lastChild)}function g(e){var t=a(e);return t?t!==w.getReactRootIDFromNodeID(t):!1}function b(e){for(;e&&e.parentNode!==e;e=e.parentNode)if(1===e.nodeType){var t=u(e);if(t){var n,r=w.getReactRootIDFromNodeID(t),o=e;do if(n=u(o),o=o.parentNode,null==o)return null;while(n!==r);if(o===$[r])return e}}return null}var _=n(24),E=n(30),N=n(6),O=n(42),C=n(43),P=n(45),w=n(46),T=n(48),x=n(49),D=n(19),M=n(51),k=n(54),S=n(55),R=n(40),I=n(59),j=n(60),A=n(63),V=n(14),L=n(20),U=n(68),F=n(71),B=n(26),W=_.ID_ATTRIBUTE_NAME,H={},K=1,q=9,z=11,Y="__ReactMount_ownerDocument$"+Math.random().toString(36).slice(2),G={},$={};if("production"!==t.env.NODE_ENV)var X={};var Q=[],Z=null,J=function(){};J.prototype.isReactComponent={},"production"!==t.env.NODE_ENV&&(J.displayName="TopLevelWrapper"),J.prototype.render=function(){return this.props};var ee={TopLevelWrapper:J,_instancesByReactRootID:G,scrollMonitor:function(e,t){t()},_updateRootComponent:function(e,n,r,i){return ee.scrollMonitor(r,function(){k.enqueueElementInternal(e,n),i&&k.enqueueCallbackInternal(e,i)}),"production"!==t.env.NODE_ENV&&(X[a(r)]=o(r)),e},_registerComponent:function(e,n){!n||n.nodeType!==K&&n.nodeType!==q&&n.nodeType!==z?"production"!==t.env.NODE_ENV?V(!1,"_registerComponent(...): Target container is not a DOM element."):V(!1):void 0,E.ensureScrollValueMonitoring();var r=ee.registerContainer(n);return G[r]=e,r},_renderNewRootComponent:function(e,n,r,a){"production"!==t.env.NODE_ENV?B(null==N.current,"_renderNewRootComponent(): Render methods should be a pure function of props and state; triggering nested component updates from render is not allowed. If necessary, trigger nested updates in componentDidUpdate. Check the render method of %s.",N.current&&N.current.getName()||"ReactCompositeComponent"):void 0;var i=A(e,null),u=ee._registerComponent(i,n);return S.batchedUpdates(m,i,u,n,r,a),"production"!==t.env.NODE_ENV&&(X[u]=o(n)),i},renderSubtreeIntoContainer:function(e,n,r,o){return null==e||null==e._reactInternalInstance?"production"!==t.env.NODE_ENV?V(!1,"parentComponent must be a valid React Component"):V(!1):void 0,ee._renderSubtreeIntoContainer(e,n,r,o)},_renderSubtreeIntoContainer:function(e,n,r,i){C.isValidElement(n)?void 0:"production"!==t.env.NODE_ENV?V(!1,"ReactDOM.render(): Invalid component element.%s","string"==typeof n?" Instead of passing an element string, make sure to instantiate it by passing it to React.createElement.":"function"==typeof n?" Instead of passing a component class, make sure to instantiate it by passing it to React.createElement.":null!=n&&void 0!==n.props?" This may be caused by unintentionally loading two independent copies of React.":""):V(!1),"production"!==t.env.NODE_ENV?B(!r||!r.tagName||"BODY"!==r.tagName.toUpperCase(),"render(): Rendering components directly into document.body is discouraged, since its children are often manipulated by third-party scripts and browser extensions. This may lead to subtle reconciliation issues. Try rendering into a container element created for your app."):void 0;var s=new C(J,null,null,null,null,null,n),l=G[a(r)];if(l){var c=l._currentElement,p=c.props;if(U(p,n)){var d=l._renderedComponent.getPublicInstance(),f=i&&function(){i.call(d)};return ee._updateRootComponent(l,s,r,f),d}ee.unmountComponentAtNode(r)}var h=o(r),v=h&&!!u(h),m=g(r);if("production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?B(!m,"render(...): Replacing React-rendered children with a new root component. If you intended to update the children of this node, you should instead have the existing children update their state and render the new components instead of calling ReactDOM.render."):void 0,!v||h.nextSibling))for(var y=h;y;){if(u(y)){"production"!==t.env.NODE_ENV?B(!1,"render(): Target node has markup rendered by React, but there are unrelated nodes as well. This is most commonly caused by white-space inserted around server-rendered markup."):void 0;break}y=y.nextSibling}var b=v&&!l&&!m,_=ee._renderNewRootComponent(s,r,b,null!=e?e._reactInternalInstance._processChildContext(e._reactInternalInstance._context):I)._renderedComponent.getPublicInstance();return i&&i.call(_),_},render:function(e,t,n){return ee._renderSubtreeIntoContainer(null,e,t,n)},registerContainer:function(e){var t=a(e);return t&&(t=w.getReactRootIDFromNodeID(t)),t||(t=w.createReactRootID()),$[t]=e,t},unmountComponentAtNode:function(e){"production"!==t.env.NODE_ENV?B(null==N.current,"unmountComponentAtNode(): Render methods should be a pure function of props and state; triggering nested component updates from render is not allowed. If necessary, trigger nested updates in componentDidUpdate. Check the render method of %s.",N.current&&N.current.getName()||"ReactCompositeComponent"):void 0,!e||e.nodeType!==K&&e.nodeType!==q&&e.nodeType!==z?"production"!==t.env.NODE_ENV?V(!1,"unmountComponentAtNode(...): Target container is not a DOM element."):V(!1):void 0;var n=a(e),r=G[n];if(!r){var o=g(e),i=u(e),s=i&&i===w.getReactRootIDFromNodeID(i);return"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?B(!o,"unmountComponentAtNode(): The node you're attempting to unmount was rendered by React and is not a top-level container. %s",s?"You may have accidentally passed in a React root node instead of its container.":"Instead, have the parent component update its state and rerender in order to remove this component."):void 0), !1}return S.batchedUpdates(y,r,e),delete G[n],delete $[n],"production"!==t.env.NODE_ENV&&delete X[n],!0},findReactContainerForID:function(e){var n=w.getReactRootIDFromNodeID(e),r=$[n];if("production"!==t.env.NODE_ENV){var o=X[n];if(o&&o.parentNode!==r){"production"!==t.env.NODE_ENV?B(u(o)===n,"ReactMount: Root element ID differed from reactRootID."):void 0;var a=r.firstChild;a&&n===u(a)?X[n]=a:"production"!==t.env.NODE_ENV?B(!1,"ReactMount: Root element has been removed from its original container. New container: %s",o.parentNode):void 0}}return r},findReactNodeByID:function(e){var t=ee.findReactContainerForID(e);return ee.findComponentRoot(t,e)},getFirstReactDOM:function(e){return b(e)},findComponentRoot:function(e,n){var r=Q,o=0,a=h(n)||e;for("production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?B(null!=a,"React can't find the root component node for data-reactid value `%s`. If you're seeing this message, it probably means that you've loaded two copies of React on the page. At this time, only a single copy of React can be loaded at a time.",n):void 0),r[0]=a.firstChild,r.length=1;o<r.length;){for(var i,u=r[o++];u;){var s=ee.getID(u);s?n===s?i=u:w.isAncestorIDOf(s,n)&&(r.length=o=0,r.push(u.firstChild)):r.push(u.firstChild),u=u.nextSibling}if(i)return r.length=0,i}r.length=0,"production"!==t.env.NODE_ENV?V(!1,"findComponentRoot(..., %s): Unable to find element. This probably means the DOM was unexpectedly mutated (e.g., by the browser), usually due to forgetting a <tbody> when using tables, nesting tags like <form>, <p>, or <a>, or using non-SVG elements in an <svg> parent. Try inspecting the child nodes of the element with React ID `%s`.",n,ee.getID(e)):V(!1)},_mountImageIntoNode:function(e,n,a,i){if(!n||n.nodeType!==K&&n.nodeType!==q&&n.nodeType!==z?"production"!==t.env.NODE_ENV?V(!1,"mountComponentIntoNode(...): Target container is not valid."):V(!1):void 0,a){var u=o(n);if(x.canReuseMarkup(e,u))return;var s=u.getAttribute(x.CHECKSUM_ATTR_NAME);u.removeAttribute(x.CHECKSUM_ATTR_NAME);var l=u.outerHTML;u.setAttribute(x.CHECKSUM_ATTR_NAME,s);var c=e;if("production"!==t.env.NODE_ENV){var p;n.nodeType===K?(p=document.createElement("div"),p.innerHTML=e,c=p.innerHTML):(p=document.createElement("iframe"),document.body.appendChild(p),p.contentDocument.write(e),c=p.contentDocument.documentElement.outerHTML,document.body.removeChild(p))}var d=r(c,l),f=" (client) "+c.substring(d-20,d+20)+"\n (server) "+l.substring(d-20,d+20);n.nodeType===q?"production"!==t.env.NODE_ENV?V(!1,"You're trying to render a component to the document using server rendering but the checksum was invalid. This usually means you rendered a different component type or props on the client from the one on the server, or your render() methods are impure. React cannot handle this case due to cross-browser quirks by rendering at the document root. You should look for environment dependent code in your components and ensure the props are the same client and server side:\n%s",f):V(!1):void 0,"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?B(!1,"React attempted to reuse markup in a container but the checksum was invalid. This generally means that you are using server rendering and the markup generated on the server was not what the client was expecting. React injected new markup to compensate which works but you have lost many of the benefits of server rendering. Instead, figure out why the markup being generated is different on the client or server:\n%s",f):void 0)}if(n.nodeType===q?"production"!==t.env.NODE_ENV?V(!1,"You're trying to render a component to the document but you didn't use server rendering. We can't do this without using server rendering due to cross-browser quirks. See ReactDOMServer.renderToString() for server rendering."):V(!1):void 0,i.useCreateElement){for(;n.lastChild;)n.removeChild(n.lastChild);n.appendChild(e)}else L(n,e)},ownerDocumentContextKey:Y,getReactRootID:a,getID:i,setID:s,getNode:l,getNodeFromInstance:c,isValid:p,purgeID:d};D.measureMethods(ee,"ReactMount",{_renderNewRootComponent:"_renderNewRootComponent",_mountImageIntoNode:"_mountImageIntoNode"}),e.exports=ee}).call(t,n(5))},function(e,t,n){"use strict";function r(e){return Object.prototype.hasOwnProperty.call(e,m)||(e[m]=h++,d[e[m]]={}),d[e[m]]}var o=n(31),a=n(32),i=n(33),u=n(38),s=n(19),l=n(39),c=n(40),p=n(41),d={},f=!1,h=0,v={topAbort:"abort",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",topVolumeChange:"volumechange",topWaiting:"waiting",topWheel:"wheel"},m="_reactListenersID"+String(Math.random()).slice(2),y=c({},u,{ReactEventListener:null,injection:{injectReactEventListener:function(e){e.setHandleTopLevel(y.handleTopLevel),y.ReactEventListener=e}},setEnabled:function(e){y.ReactEventListener&&y.ReactEventListener.setEnabled(e)},isEnabled:function(){return!(!y.ReactEventListener||!y.ReactEventListener.isEnabled())},listenTo:function(e,t){for(var n=t,a=r(n),u=i.registrationNameDependencies[e],s=o.topLevelTypes,l=0;l<u.length;l++){var c=u[l];a.hasOwnProperty(c)&&a[c]||(c===s.topWheel?p("wheel")?y.ReactEventListener.trapBubbledEvent(s.topWheel,"wheel",n):p("mousewheel")?y.ReactEventListener.trapBubbledEvent(s.topWheel,"mousewheel",n):y.ReactEventListener.trapBubbledEvent(s.topWheel,"DOMMouseScroll",n):c===s.topScroll?p("scroll",!0)?y.ReactEventListener.trapCapturedEvent(s.topScroll,"scroll",n):y.ReactEventListener.trapBubbledEvent(s.topScroll,"scroll",y.ReactEventListener.WINDOW_HANDLE):c===s.topFocus||c===s.topBlur?(p("focus",!0)?(y.ReactEventListener.trapCapturedEvent(s.topFocus,"focus",n),y.ReactEventListener.trapCapturedEvent(s.topBlur,"blur",n)):p("focusin")&&(y.ReactEventListener.trapBubbledEvent(s.topFocus,"focusin",n),y.ReactEventListener.trapBubbledEvent(s.topBlur,"focusout",n)),a[s.topBlur]=!0,a[s.topFocus]=!0):v.hasOwnProperty(c)&&y.ReactEventListener.trapBubbledEvent(c,v[c],n),a[c]=!0)}},trapBubbledEvent:function(e,t,n){return y.ReactEventListener.trapBubbledEvent(e,t,n)},trapCapturedEvent:function(e,t,n){return y.ReactEventListener.trapCapturedEvent(e,t,n)},ensureScrollValueMonitoring:function(){if(!f){var e=l.refreshScrollValues;y.ReactEventListener.monitorScrollValue(e),f=!0}},eventNameDispatchConfigs:a.eventNameDispatchConfigs,registrationNameModules:a.registrationNameModules,putListener:a.putListener,getListener:a.getListener,deleteListener:a.deleteListener,deleteAllListeners:a.deleteAllListeners});s.measureMethods(y,"ReactBrowserEventEmitter",{putListener:"putListener",deleteListener:"deleteListener"}),e.exports=y},function(e,t,n){"use strict";var r=n(18),o=r({bubbled:null,captured:null}),a=r({topAbort:null,topBlur:null,topCanPlay:null,topCanPlayThrough:null,topChange:null,topClick:null,topCompositionEnd:null,topCompositionStart:null,topCompositionUpdate:null,topContextMenu:null,topCopy:null,topCut:null,topDoubleClick:null,topDrag:null,topDragEnd:null,topDragEnter:null,topDragExit:null,topDragLeave:null,topDragOver:null,topDragStart:null,topDrop:null,topDurationChange:null,topEmptied:null,topEncrypted:null,topEnded:null,topError:null,topFocus:null,topInput:null,topKeyDown:null,topKeyPress:null,topKeyUp:null,topLoad:null,topLoadedData:null,topLoadedMetadata:null,topLoadStart:null,topMouseDown:null,topMouseMove:null,topMouseOut:null,topMouseOver:null,topMouseUp:null,topPaste:null,topPause:null,topPlay:null,topPlaying:null,topProgress:null,topRateChange:null,topReset:null,topScroll:null,topSeeked:null,topSeeking:null,topSelectionChange:null,topStalled:null,topSubmit:null,topSuspend:null,topTextInput:null,topTimeUpdate:null,topTouchCancel:null,topTouchEnd:null,topTouchMove:null,topTouchStart:null,topVolumeChange:null,topWaiting:null,topWheel:null}),i={topLevelTypes:a,PropagationPhases:o};e.exports=i},function(e,t,n){(function(t){"use strict";function r(){var e=m&&m.traverseTwoPhase&&m.traverseEnterLeave;"production"!==t.env.NODE_ENV?c(e,"InstanceHandle not injected before use!"):void 0}var o=n(33),a=n(34),i=n(35),u=n(36),s=n(37),l=n(14),c=n(26),p={},d=null,f=function(e,t){e&&(a.executeDispatchesInOrder(e,t),e.isPersistent()||e.constructor.release(e))},h=function(e){return f(e,!0)},v=function(e){return f(e,!1)},m=null,y={injection:{injectMount:a.injection.injectMount,injectInstanceHandle:function(e){m=e,"production"!==t.env.NODE_ENV&&r()},getInstanceHandle:function(){return"production"!==t.env.NODE_ENV&&r(),m},injectEventPluginOrder:o.injectEventPluginOrder,injectEventPluginsByName:o.injectEventPluginsByName},eventNameDispatchConfigs:o.eventNameDispatchConfigs,registrationNameModules:o.registrationNameModules,putListener:function(e,n,r){"function"!=typeof r?"production"!==t.env.NODE_ENV?l(!1,"Expected %s listener to be a function, instead got type %s",n,typeof r):l(!1):void 0;var a=p[n]||(p[n]={});a[e]=r;var i=o.registrationNameModules[n];i&&i.didPutListener&&i.didPutListener(e,n,r)},getListener:function(e,t){var n=p[t];return n&&n[e]},deleteListener:function(e,t){var n=o.registrationNameModules[t];n&&n.willDeleteListener&&n.willDeleteListener(e,t);var r=p[t];r&&delete r[e]},deleteAllListeners:function(e){for(var t in p)if(p[t][e]){var n=o.registrationNameModules[t];n&&n.willDeleteListener&&n.willDeleteListener(e,t),delete p[t][e]}},extractEvents:function(e,t,n,r,a){for(var i,s=o.plugins,l=0;l<s.length;l++){var c=s[l];if(c){var p=c.extractEvents(e,t,n,r,a);p&&(i=u(i,p))}}return i},enqueueEvents:function(e){e&&(d=u(d,e))},processEventQueue:function(e){var n=d;d=null,e?s(n,h):s(n,v),d?"production"!==t.env.NODE_ENV?l(!1,"processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented."):l(!1):void 0,i.rethrowCaughtError()},__purge:function(){p={}},__getListenerBank:function(){return p}};e.exports=y}).call(t,n(5))},function(e,t,n){(function(t){"use strict";function r(){if(u)for(var e in s){var n=s[e],r=u.indexOf(e);if(r>-1?void 0:"production"!==t.env.NODE_ENV?i(!1,"EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `%s`.",e):i(!1),!l.plugins[r]){n.extractEvents?void 0:"production"!==t.env.NODE_ENV?i(!1,"EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `%s` does not.",e):i(!1),l.plugins[r]=n;var a=n.eventTypes;for(var c in a)o(a[c],n,c)?void 0:"production"!==t.env.NODE_ENV?i(!1,"EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.",c,e):i(!1)}}}function o(e,n,r){l.eventNameDispatchConfigs.hasOwnProperty(r)?"production"!==t.env.NODE_ENV?i(!1,"EventPluginHub: More than one plugin attempted to publish the same event name, `%s`.",r):i(!1):void 0,l.eventNameDispatchConfigs[r]=e;var o=e.phasedRegistrationNames;if(o){for(var u in o)if(o.hasOwnProperty(u)){var s=o[u];a(s,n,r)}return!0}return e.registrationName?(a(e.registrationName,n,r),!0):!1}function a(e,n,r){l.registrationNameModules[e]?"production"!==t.env.NODE_ENV?i(!1,"EventPluginHub: More than one plugin attempted to publish the same registration name, `%s`.",e):i(!1):void 0,l.registrationNameModules[e]=n,l.registrationNameDependencies[e]=n.eventTypes[r].dependencies}var i=n(14),u=null,s={},l={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},injectEventPluginOrder:function(e){u?"production"!==t.env.NODE_ENV?i(!1,"EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React."):i(!1):void 0,u=Array.prototype.slice.call(e),r()},injectEventPluginsByName:function(e){var n=!1;for(var o in e)if(e.hasOwnProperty(o)){var a=e[o];s.hasOwnProperty(o)&&s[o]===a||(s[o]?"production"!==t.env.NODE_ENV?i(!1,"EventPluginRegistry: Cannot inject two different event plugins using the same name, `%s`.",o):i(!1):void 0,s[o]=a,n=!0)}n&&r()},getPluginModuleForEvent:function(e){var t=e.dispatchConfig;if(t.registrationName)return l.registrationNameModules[t.registrationName]||null;for(var n in t.phasedRegistrationNames)if(t.phasedRegistrationNames.hasOwnProperty(n)){var r=l.registrationNameModules[t.phasedRegistrationNames[n]];if(r)return r}return null},_resetEventPlugins:function(){u=null;for(var e in s)s.hasOwnProperty(e)&&delete s[e];l.plugins.length=0;var t=l.eventNameDispatchConfigs;for(var n in t)t.hasOwnProperty(n)&&delete t[n];var r=l.registrationNameModules;for(var o in r)r.hasOwnProperty(o)&&delete r[o]}};e.exports=l}).call(t,n(5))},function(e,t,n){(function(t){"use strict";function r(e){return e===g.topMouseUp||e===g.topTouchEnd||e===g.topTouchCancel}function o(e){return e===g.topMouseMove||e===g.topTouchMove}function a(e){return e===g.topMouseDown||e===g.topTouchStart}function i(e,t,n,r){var o=e.type||"unknown-event";e.currentTarget=y.Mount.getNode(r),t?h.invokeGuardedCallbackWithCatch(o,n,e,r):h.invokeGuardedCallback(o,n,e,r),e.currentTarget=null}function u(e,n){var r=e._dispatchListeners,o=e._dispatchIDs;if("production"!==t.env.NODE_ENV&&d(e),Array.isArray(r))for(var a=0;a<r.length&&!e.isPropagationStopped();a++)i(e,n,r[a],o[a]);else r&&i(e,n,r,o);e._dispatchListeners=null,e._dispatchIDs=null}function s(e){var n=e._dispatchListeners,r=e._dispatchIDs;if("production"!==t.env.NODE_ENV&&d(e),Array.isArray(n)){for(var o=0;o<n.length&&!e.isPropagationStopped();o++)if(n[o](e,r[o]))return r[o]}else if(n&&n(e,r))return r;return null}function l(e){var t=s(e);return e._dispatchIDs=null,e._dispatchListeners=null,t}function c(e){"production"!==t.env.NODE_ENV&&d(e);var n=e._dispatchListeners,r=e._dispatchIDs;Array.isArray(n)?"production"!==t.env.NODE_ENV?v(!1,"executeDirectDispatch(...): Invalid `event`."):v(!1):void 0;var o=n?n(e,r):null;return e._dispatchListeners=null,e._dispatchIDs=null,o}function p(e){return!!e._dispatchListeners}var d,f=n(31),h=n(35),v=n(14),m=n(26),y={Mount:null,injectMount:function(e){y.Mount=e,"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?m(e&&e.getNode&&e.getID,"EventPluginUtils.injection.injectMount(...): Injected Mount module is missing getNode or getID."):void 0)}},g=f.topLevelTypes;"production"!==t.env.NODE_ENV&&(d=function(e){var n=e._dispatchListeners,r=e._dispatchIDs,o=Array.isArray(n),a=Array.isArray(r),i=a?r.length:r?1:0,u=o?n.length:n?1:0;"production"!==t.env.NODE_ENV?m(a===o&&i===u,"EventPluginUtils: Invalid `event`."):void 0});var b={isEndish:r,isMoveish:o,isStartish:a,executeDirectDispatch:c,executeDispatchesInOrder:u,executeDispatchesInOrderStopAtTrue:l,hasDispatches:p,getNode:function(e){return y.Mount.getNode(e)},getID:function(e){return y.Mount.getID(e)},injection:y};e.exports=b}).call(t,n(5))},function(e,t,n){(function(t){"use strict";function n(e,t,n,o){try{return t(n,o)}catch(a){return void(null===r&&(r=a))}}var r=null,o={invokeGuardedCallback:n,invokeGuardedCallbackWithCatch:n,rethrowCaughtError:function(){if(r){var e=r;throw r=null,e}}};if("production"!==t.env.NODE_ENV&&"undefined"!=typeof window&&"function"==typeof window.dispatchEvent&&"undefined"!=typeof document&&"function"==typeof document.createEvent){var a=document.createElement("react");o.invokeGuardedCallback=function(e,t,n,r){var o=t.bind(null,n,r),i="react-"+e;a.addEventListener(i,o,!1);var u=document.createEvent("Event");u.initEvent(i,!1,!1),a.dispatchEvent(u),a.removeEventListener(i,o,!1)}}e.exports=o}).call(t,n(5))},function(e,t,n){(function(t){"use strict";function r(e,n){if(null==n?"production"!==t.env.NODE_ENV?o(!1,"accumulateInto(...): Accumulated items must not be null or undefined."):o(!1):void 0,null==e)return n;var r=Array.isArray(e),a=Array.isArray(n);return r&&a?(e.push.apply(e,n),e):r?(e.push(n),e):a?[e].concat(n):[e,n]}var o=n(14);e.exports=r}).call(t,n(5))},function(e,t){"use strict";var n=function(e,t,n){Array.isArray(e)?e.forEach(t,n):e&&t.call(n,e)};e.exports=n},function(e,t,n){"use strict";function r(e){o.enqueueEvents(e),o.processEventQueue(!1)}var o=n(32),a={handleTopLevel:function(e,t,n,a,i){var u=o.extractEvents(e,t,n,a,i);r(u)}};e.exports=a},function(e,t){"use strict";var n={currentScrollLeft:0,currentScrollTop:0,refreshScrollValues:function(e){n.currentScrollLeft=e.x,n.currentScrollTop=e.y}};e.exports=n},function(e,t){"use strict";function n(e,t){if(null==e)throw new TypeError("Object.assign target cannot be null or undefined");for(var n=Object(e),r=Object.prototype.hasOwnProperty,o=1;o<arguments.length;o++){var a=arguments[o];if(null!=a){var i=Object(a);for(var u in i)r.call(i,u)&&(n[u]=i[u])}}return n}e.exports=n},function(e,t,n){"use strict";/** * Checks if an event is supported in the current execution environment. * * NOTE: This will not work correctly for non-generic events such as `change`, * `reset`, `load`, `error`, and `select`. * * Borrows from Modernizr. * * @param {string} eventNameSuffix Event name, e.g. "click". * @param {?boolean} capture Check if the capture phase is supported. * @return {boolean} True if the event is supported. * @internal * @license Modernizr 3.0.0pre (Custom Build) | MIT */ function r(e,t){if(!a.canUseDOM||t&&!("addEventListener"in document))return!1;var n="on"+e,r=n in document;if(!r){var i=document.createElement("div");i.setAttribute(n,"return;"),r="function"==typeof i[n]}return!r&&o&&"wheel"===e&&(r=document.implementation.hasFeature("Events.wheel","3.0")),r}var o,a=n(10);a.canUseDOM&&(o=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature("","")!==!0),e.exports=r},function(e,t){"use strict";var n={useCreateElement:!1};e.exports=n},function(e,t,n){(function(t){"use strict";var r=n(6),o=n(40),a=n(44),i="function"==typeof Symbol&&Symbol["for"]&&Symbol["for"]("react.element")||60103,u={key:!0,ref:!0,__self:!0,__source:!0},s=function(e,n,r,o,u,s,l){var c={$$typeof:i,type:e,key:n,ref:r,props:l,_owner:s};return"production"!==t.env.NODE_ENV&&(c._store={},a?(Object.defineProperty(c._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(c,"_self",{configurable:!1,enumerable:!1,writable:!1,value:o}),Object.defineProperty(c,"_source",{configurable:!1,enumerable:!1,writable:!1,value:u})):(c._store.validated=!1,c._self=o,c._source=u),Object.freeze(c.props),Object.freeze(c)),c};s.createElement=function(e,t,n){var o,a={},i=null,l=null,c=null,p=null;if(null!=t){l=void 0===t.ref?null:t.ref,i=void 0===t.key?null:""+t.key,c=void 0===t.__self?null:t.__self,p=void 0===t.__source?null:t.__source;for(o in t)t.hasOwnProperty(o)&&!u.hasOwnProperty(o)&&(a[o]=t[o])}var d=arguments.length-2;if(1===d)a.children=n;else if(d>1){for(var f=Array(d),h=0;d>h;h++)f[h]=arguments[h+2];a.children=f}if(e&&e.defaultProps){var v=e.defaultProps;for(o in v)"undefined"==typeof a[o]&&(a[o]=v[o])}return s(e,i,l,c,p,r.current,a)},s.createFactory=function(e){var t=s.createElement.bind(null,e);return t.type=e,t},s.cloneAndReplaceKey=function(e,t){var n=s(e.type,t,e.ref,e._self,e._source,e._owner,e.props);return n},s.cloneAndReplaceProps=function(e,n){var r=s(e.type,e.key,e.ref,e._self,e._source,e._owner,n);return"production"!==t.env.NODE_ENV&&(r._store.validated=e._store.validated),r},s.cloneElement=function(e,t,n){var a,i=o({},e.props),l=e.key,c=e.ref,p=e._self,d=e._source,f=e._owner;if(null!=t){void 0!==t.ref&&(c=t.ref,f=r.current),void 0!==t.key&&(l=""+t.key);for(a in t)t.hasOwnProperty(a)&&!u.hasOwnProperty(a)&&(i[a]=t[a])}var h=arguments.length-2;if(1===h)i.children=n;else if(h>1){for(var v=Array(h),m=0;h>m;m++)v[m]=arguments[m+2];i.children=v}return s(e.type,l,c,p,d,f,i)},s.isValidElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===i},e.exports=s}).call(t,n(5))},function(e,t,n){(function(t){"use strict";var n=!1;if("production"!==t.env.NODE_ENV)try{Object.defineProperty({},"x",{get:function(){}}),n=!0}catch(r){}e.exports=n}).call(t,n(5))},function(e,t){"use strict";function n(e){return!!a[e]}function r(e){a[e]=!0}function o(e){delete a[e]}var a={},i={isNullComponentID:n,registerNullComponentID:r,deregisterNullComponentID:o};e.exports=i},function(e,t,n){(function(t){"use strict";function r(e){return f+e.toString(36)}function o(e,t){return e.charAt(t)===f||t===e.length}function a(e){return""===e||e.charAt(0)===f&&e.charAt(e.length-1)!==f}function i(e,t){return 0===t.indexOf(e)&&o(t,e.length)}function u(e){return e?e.substr(0,e.lastIndexOf(f)):""}function s(e,n){if(a(e)&&a(n)?void 0:"production"!==t.env.NODE_ENV?d(!1,"getNextDescendantID(%s, %s): Received an invalid React DOM ID.",e,n):d(!1),i(e,n)?void 0:"production"!==t.env.NODE_ENV?d(!1,"getNextDescendantID(...): React has made an invalid assumption about the DOM hierarchy. Expected `%s` to be an ancestor of `%s`.",e,n):d(!1),e===n)return e;var r,u=e.length+h;for(r=u;r<n.length&&!o(n,r);r++);return n.substr(0,r)}function l(e,n){var r=Math.min(e.length,n.length);if(0===r)return"";for(var i=0,u=0;r>=u;u++)if(o(e,u)&&o(n,u))i=u;else if(e.charAt(u)!==n.charAt(u))break;var s=e.substr(0,i);return a(s)?void 0:"production"!==t.env.NODE_ENV?d(!1,"getFirstCommonAncestorID(%s, %s): Expected a valid React DOM ID: %s",e,n,s):d(!1),s}function c(e,n,r,o,a,l){e=e||"",n=n||"",e===n?"production"!==t.env.NODE_ENV?d(!1,"traverseParentPath(...): Cannot traverse from and to the same ID, `%s`.",e):d(!1):void 0;var c=i(n,e);c||i(e,n)?void 0:"production"!==t.env.NODE_ENV?d(!1,"traverseParentPath(%s, %s, ...): Cannot traverse from two IDs that do not have a parent path.",e,n):d(!1);for(var p=0,f=c?u:s,h=e;;h=f(h,n)){var m;if(a&&h===e||l&&h===n||(m=r(h,c,o)),m===!1||h===n)break;p++<v?void 0:"production"!==t.env.NODE_ENV?d(!1,"traverseParentPath(%s, %s, ...): Detected an infinite loop while traversing the React DOM ID tree. This may be due to malformed IDs: %s",e,n,h):d(!1)}}var p=n(47),d=n(14),f=".",h=f.length,v=1e4,m={createReactRootID:function(){return r(p.createReactRootIndex())},createReactID:function(e,t){return e+t},getReactRootIDFromNodeID:function(e){if(e&&e.charAt(0)===f&&e.length>1){var t=e.indexOf(f,1);return t>-1?e.substr(0,t):e}return null},traverseEnterLeave:function(e,t,n,r,o){var a=l(e,t);a!==e&&c(e,a,n,r,!1,!0),a!==t&&c(a,t,n,o,!0,!1)},traverseTwoPhase:function(e,t,n){e&&(c("",e,t,n,!0,!1),c(e,"",t,n,!1,!0))},traverseTwoPhaseSkipTarget:function(e,t,n){e&&(c("",e,t,n,!0,!0),c(e,"",t,n,!0,!0))},traverseAncestors:function(e,t,n){c("",e,t,n,!0,!1)},getFirstCommonAncestorID:l,_getNextDescendantID:s,isAncestorIDOf:i,SEPARATOR:f};e.exports=m}).call(t,n(5))},function(e,t){"use strict";var n={injectCreateReactRootIndex:function(e){r.createReactRootIndex=e}},r={createReactRootIndex:null,injection:n};e.exports=r},function(e,t){"use strict";var n={remove:function(e){e._reactInternalInstance=void 0},get:function(e){return e._reactInternalInstance},has:function(e){return void 0!==e._reactInternalInstance},set:function(e,t){e._reactInternalInstance=t}};e.exports=n},function(e,t,n){"use strict";var r=n(50),o=/\/?>/,a={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(e){var t=r(e);return e.replace(o," "+a.CHECKSUM_ATTR_NAME+'="'+t+'"$&')},canReuseMarkup:function(e,t){var n=t.getAttribute(a.CHECKSUM_ATTR_NAME);n=n&&parseInt(n,10);var o=r(e);return o===n}};e.exports=a},function(e,t){"use strict";function n(e){for(var t=1,n=0,o=0,a=e.length,i=-4&a;i>o;){for(;o<Math.min(o+4096,i);o+=4)n+=(t+=e.charCodeAt(o))+(t+=e.charCodeAt(o+1))+(t+=e.charCodeAt(o+2))+(t+=e.charCodeAt(o+3));t%=r,n%=r}for(;a>o;o++)n+=t+=e.charCodeAt(o);return t%=r,n%=r,t|n<<16}var r=65521;e.exports=n},function(e,t,n){"use strict";function r(){o.attachRefs(this,this._currentElement)}var o=n(52),a={mountComponent:function(e,t,n,o){var a=e.mountComponent(t,n,o);return e._currentElement&&null!=e._currentElement.ref&&n.getReactMountReady().enqueue(r,e),a},unmountComponent:function(e){o.detachRefs(e,e._currentElement),e.unmountComponent()},receiveComponent:function(e,t,n,a){var i=e._currentElement;if(t!==i||a!==e._context){var u=o.shouldUpdateRefs(i,t);u&&o.detachRefs(e,i),e.receiveComponent(t,n,a),u&&e._currentElement&&null!=e._currentElement.ref&&n.getReactMountReady().enqueue(r,e)}},performUpdateIfNecessary:function(e,t){e.performUpdateIfNecessary(t)}};e.exports=a},function(e,t,n){"use strict";function r(e,t,n){"function"==typeof e?e(t.getPublicInstance()):a.addComponentAsRefTo(t,e,n)}function o(e,t,n){"function"==typeof e?e(null):a.removeComponentAsRefFrom(t,e,n)}var a=n(53),i={};i.attachRefs=function(e,t){if(null!==t&&t!==!1){var n=t.ref;null!=n&&r(n,e,t._owner)}},i.shouldUpdateRefs=function(e,t){var n=null===e||e===!1,r=null===t||t===!1;return n||r||t._owner!==e._owner||t.ref!==e.ref},i.detachRefs=function(e,t){if(null!==t&&t!==!1){var n=t.ref;null!=n&&o(n,e,t._owner)}},e.exports=i},function(e,t,n){(function(t){"use strict";var r=n(14),o={isValidOwner:function(e){return!(!e||"function"!=typeof e.attachRef||"function"!=typeof e.detachRef)},addComponentAsRefTo:function(e,n,a){o.isValidOwner(a)?void 0:"production"!==t.env.NODE_ENV?r(!1,"addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's `render` method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner)."):r(!1),a.attachRef(n,e)},removeComponentAsRefFrom:function(e,n,a){o.isValidOwner(a)?void 0:"production"!==t.env.NODE_ENV?r(!1,"removeComponentAsRefFrom(...): Only a ReactOwner can have refs. You might be removing a ref to a component that was not created inside a component's `render` method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner)."):r(!1),a.getPublicInstance().refs[n]===e.getPublicInstance()&&a.detachRef(n)}};e.exports=o}).call(t,n(5))},function(e,t,n){(function(t){"use strict";function r(e){s.enqueueUpdate(e)}function o(e,n){var r=u.get(e);return r?("production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?p(null==a.current,"%s(...): Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.",n):void 0),r):("production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?p(!n,"%s(...): Can only update a mounted or mounting component. This usually means you called %s() on an unmounted component. This is a no-op. Please check the code for the %s component.",n,n,e.constructor.displayName):void 0),null)}var a=n(6),i=n(43),u=n(48),s=n(55),l=n(40),c=n(14),p=n(26),d={isMounted:function(e){if("production"!==t.env.NODE_ENV){var n=a.current;null!==n&&("production"!==t.env.NODE_ENV?p(n._warnedAboutRefsInRender,"%s is accessing isMounted inside its render() function. render() should be a pure function of props and state. It should never access something that requires stale data from the previous render, such as refs. Move this logic to componentDidMount and componentDidUpdate instead.",n.getName()||"A component"):void 0,n._warnedAboutRefsInRender=!0)}var r=u.get(e);return r?!!r._renderedComponent:!1},enqueueCallback:function(e,n){"function"!=typeof n?"production"!==t.env.NODE_ENV?c(!1,"enqueueCallback(...): You called `setProps`, `replaceProps`, `setState`, `replaceState`, or `forceUpdate` with a callback that isn't callable."):c(!1):void 0;var a=o(e);return a?(a._pendingCallbacks?a._pendingCallbacks.push(n):a._pendingCallbacks=[n],void r(a)):null},enqueueCallbackInternal:function(e,n){"function"!=typeof n?"production"!==t.env.NODE_ENV?c(!1,"enqueueCallback(...): You called `setProps`, `replaceProps`, `setState`, `replaceState`, or `forceUpdate` with a callback that isn't callable."):c(!1):void 0,e._pendingCallbacks?e._pendingCallbacks.push(n):e._pendingCallbacks=[n],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 a=n._pendingStateQueue||(n._pendingStateQueue=[]);a.push(t),r(n)}},enqueueSetProps:function(e,t){var n=o(e,"setProps");n&&d.enqueueSetPropsInternal(n,t)},enqueueSetPropsInternal:function(e,n){var o=e._topLevelWrapper;o?void 0:"production"!==t.env.NODE_ENV?c(!1,"setProps(...): You called `setProps` on a component with a parent. This is an anti-pattern since props will get reactively updated when rendered. Instead, change the owner's `render` method to pass the correct value as props to the component where it is created."):c(!1);var a=o._pendingElement||o._currentElement,u=a.props,s=l({},u.props,n);o._pendingElement=i.cloneAndReplaceProps(a,i.cloneAndReplaceProps(u,s)),r(o)},enqueueReplaceProps:function(e,t){var n=o(e,"replaceProps");n&&d.enqueueReplacePropsInternal(n,t)},enqueueReplacePropsInternal:function(e,n){var o=e._topLevelWrapper;o?void 0:"production"!==t.env.NODE_ENV?c(!1,"replaceProps(...): You called `replaceProps` on a component with a parent. This is an anti-pattern since props will get reactively updated when rendered. Instead, change the owner's `render` method to pass the correct value as props to the component where it is created."):c(!1);var a=o._pendingElement||o._currentElement,u=a.props;o._pendingElement=i.cloneAndReplaceProps(a,i.cloneAndReplaceProps(u,n)),r(o)},enqueueElementInternal:function(e,t){e._pendingElement=t,r(e)}};e.exports=d}).call(t,n(5))},function(e,t,n){(function(t){"use strict";function r(){w.ReactReconcileTransaction&&_?void 0:"production"!==t.env.NODE_ENV?m(!1,"ReactUpdates: must inject a reconcile transaction class and batching strategy"):m(!1)}function o(){this.reinitializeTransaction(),this.dirtyComponentsLength=null,this.callbackQueue=c.getPooled(),this.reconcileTransaction=w.ReactReconcileTransaction.getPooled(!1)}function a(e,t,n,o,a,i){r(),_.batchedUpdates(e,t,n,o,a,i)}function i(e,t){return e._mountOrder-t._mountOrder}function u(e){var n=e.dirtyComponentsLength;n!==y.length?"production"!==t.env.NODE_ENV?m(!1,"Expected flush transaction's stored dirty-components length (%s) to match dirty-components array length (%s).",n,y.length):m(!1):void 0,y.sort(i);for(var r=0;n>r;r++){var o=y[r],a=o._pendingCallbacks;if(o._pendingCallbacks=null,f.performUpdateIfNecessary(o,e.reconcileTransaction),a)for(var u=0;u<a.length;u++)e.callbackQueue.enqueue(a[u],o.getPublicInstance())}}function s(e){return r(),_.isBatchingUpdates?void y.push(e):void _.batchedUpdates(s,e)}function l(e,n){_.isBatchingUpdates?void 0:"production"!==t.env.NODE_ENV?m(!1,"ReactUpdates.asap: Can't enqueue an asap callback in a context whereupdates are not being batched."):m(!1),g.enqueue(e,n),b=!0}var c=n(56),p=n(57),d=n(19),f=n(51),h=n(58),v=n(40),m=n(14),y=[],g=c.getPooled(),b=!1,_=null,E={initialize:function(){this.dirtyComponentsLength=y.length},close:function(){this.dirtyComponentsLength!==y.length?(y.splice(0,this.dirtyComponentsLength),C()):y.length=0}},N={initialize:function(){this.callbackQueue.reset()},close:function(){this.callbackQueue.notifyAll()}},O=[E,N];v(o.prototype,h.Mixin,{getTransactionWrappers:function(){return O},destructor:function(){this.dirtyComponentsLength=null,c.release(this.callbackQueue),this.callbackQueue=null,w.ReactReconcileTransaction.release(this.reconcileTransaction),this.reconcileTransaction=null},perform:function(e,t,n){return h.Mixin.perform.call(this,this.reconcileTransaction.perform,this.reconcileTransaction,e,t,n)}}),p.addPoolingTo(o);var C=function(){for(;y.length||b;){if(y.length){var e=o.getPooled();e.perform(u,null,e),o.release(e)}if(b){b=!1;var t=g;g=c.getPooled(),t.notifyAll(),c.release(t)}}};C=d.measure("ReactUpdates","flushBatchedUpdates",C);var P={injectReconcileTransaction:function(e){e?void 0:"production"!==t.env.NODE_ENV?m(!1,"ReactUpdates: must provide a reconcile transaction class"):m(!1),w.ReactReconcileTransaction=e},injectBatchingStrategy:function(e){e?void 0:"production"!==t.env.NODE_ENV?m(!1,"ReactUpdates: must provide a batching strategy"):m(!1),"function"!=typeof e.batchedUpdates?"production"!==t.env.NODE_ENV?m(!1,"ReactUpdates: must provide a batchedUpdates() function"):m(!1):void 0,"boolean"!=typeof e.isBatchingUpdates?"production"!==t.env.NODE_ENV?m(!1,"ReactUpdates: must provide an isBatchingUpdates boolean attribute"):m(!1):void 0,_=e}},w={ReactReconcileTransaction:null,batchedUpdates:a,enqueueUpdate:s,flushBatchedUpdates:C,injection:P,asap:l};e.exports=w}).call(t,n(5))},function(e,t,n){(function(t){"use strict";function r(){this._callbacks=null,this._contexts=null}var o=n(57),a=n(40),i=n(14);a(r.prototype,{enqueue:function(e,t){this._callbacks=this._callbacks||[],this._contexts=this._contexts||[],this._callbacks.push(e),this._contexts.push(t)},notifyAll:function(){var e=this._callbacks,n=this._contexts;if(e){e.length!==n.length?"production"!==t.env.NODE_ENV?i(!1,"Mismatched list of contexts in callback queue"):i(!1):void 0,this._callbacks=null,this._contexts=null;for(var r=0;r<e.length;r++)e[r].call(n[r]);e.length=0,n.length=0}},reset:function(){this._callbacks=null,this._contexts=null},destructor:function(){this.reset()}}),o.addPoolingTo(r),e.exports=r}).call(t,n(5))},function(e,t,n){(function(t){"use strict";var r=n(14),o=function(e){var t=this;if(t.instancePool.length){var n=t.instancePool.pop();return t.call(n,e),n}return new t(e)},a=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)},i=function(e,t,n){var r=this;if(r.instancePool.length){var o=r.instancePool.pop();return r.call(o,e,t,n),o}return new r(e,t,n)},u=function(e,t,n,r){var o=this;if(o.instancePool.length){var a=o.instancePool.pop();return o.call(a,e,t,n,r),a}return new o(e,t,n,r)},s=function(e,t,n,r,o){var a=this;if(a.instancePool.length){var i=a.instancePool.pop();return a.call(i,e,t,n,r,o),i}return new a(e,t,n,r,o)},l=function(e){var n=this;e instanceof n?void 0:"production"!==t.env.NODE_ENV?r(!1,"Trying to release an instance into a pool of a different type."):r(!1),e.destructor(),n.instancePool.length<n.poolSize&&n.instancePool.push(e)},c=10,p=o,d=function(e,t){var n=e;return n.instancePool=[],n.getPooled=t||p,n.poolSize||(n.poolSize=c),n.release=l,n},f={addPoolingTo:d,oneArgumentPooler:o,twoArgumentPooler:a,threeArgumentPooler:i,fourArgumentPooler:u,fiveArgumentPooler:s};e.exports=f}).call(t,n(5))},function(e,t,n){(function(t){"use strict";var r=n(14),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,n,o,a,i,u,s,l){this.isInTransaction()?"production"!==t.env.NODE_ENV?r(!1,"Transaction.perform(...): Cannot initialize a transaction when there is already an outstanding transaction."):r(!1):void 0;var c,p;try{this._isInTransaction=!0,c=!0,this.initializeAll(0),p=e.call(n,o,a,i,u,s,l),c=!1}finally{try{if(c)try{this.closeAll(0)}catch(d){}else this.closeAll(0)}finally{this._isInTransaction=!1}}return p},initializeAll:function(e){for(var t=this.transactionWrappers,n=e;n<t.length;n++){var r=t[n];try{this.wrapperInitData[n]=a.OBSERVED_ERROR,this.wrapperInitData[n]=r.initialize?r.initialize.call(this):null}finally{if(this.wrapperInitData[n]===a.OBSERVED_ERROR)try{this.initializeAll(n+1)}catch(o){}}}},closeAll:function(e){this.isInTransaction()?void 0:"production"!==t.env.NODE_ENV?r(!1,"Transaction.closeAll(): Cannot close transaction when none are open."):r(!1);for(var n=this.transactionWrappers,o=e;o<n.length;o++){var i,u=n[o],s=this.wrapperInitData[o];try{i=!0,s!==a.OBSERVED_ERROR&&u.close&&u.close.call(this,s),i=!1}finally{if(i)try{this.closeAll(o+1)}catch(l){}}}this.wrapperInitData.length=0}},a={Mixin:o,OBSERVED_ERROR:{}};e.exports=a}).call(t,n(5))},function(e,t,n){(function(t){"use strict";var n={};"production"!==t.env.NODE_ENV&&Object.freeze(n),e.exports=n}).call(t,n(5))},function(e,t,n){"use strict";function r(e,t){var n=!0;e:for(;n;){var r=e,a=t;if(n=!1,r&&a){if(r===a)return!0;if(o(r))return!1;if(o(a)){e=r,t=a.parentNode,n=!0;continue e}return r.contains?r.contains(a):r.compareDocumentPosition?!!(16&r.compareDocumentPosition(a)):!1}return!1}}var o=n(61);e.exports=r},function(e,t,n){"use strict";function r(e){return o(e)&&3==e.nodeType}var o=n(62);e.exports=r},function(e,t){"use strict";function n(e){return!(!e||!("function"==typeof Node?e instanceof Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName))}e.exports=n},function(e,t,n){(function(t){"use strict";function r(e){if(e){var t=e.getName();if(t)return" Check the render method of `"+t+"`."}return""}function o(e){return"function"==typeof e&&"undefined"!=typeof e.prototype&&"function"==typeof e.prototype.mountComponent&&"function"==typeof e.prototype.receiveComponent}function a(e){var n;if(null===e||e===!1)n=new u(a);else if("object"==typeof e){var i=e;!i||"function"!=typeof i.type&&"string"!=typeof i.type?"production"!==t.env.NODE_ENV?c(!1,"Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",null==i.type?i.type:typeof i.type,r(i._owner)):c(!1):void 0,n="string"==typeof i.type?s.createInternalComponent(i):o(i.type)?new i.type(i):new d}else"string"==typeof e||"number"==typeof e?n=s.createInstanceForText(e):"production"!==t.env.NODE_ENV?c(!1,"Encountered invalid React node of type %s",typeof e):c(!1);return"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?p("function"==typeof n.construct&&"function"==typeof n.mountComponent&&"function"==typeof n.receiveComponent&&"function"==typeof n.unmountComponent,"Only React Components can be mounted."):void 0),n.construct(e),n._mountIndex=0,n._mountImage=null,"production"!==t.env.NODE_ENV&&(n._isOwnerNecessary=!1,n._warnedAboutRefsInRender=!1),"production"!==t.env.NODE_ENV&&Object.preventExtensions&&Object.preventExtensions(n),n}var i=n(64),u=n(69),s=n(70),l=n(40),c=n(14),p=n(26),d=function(){};l(d.prototype,i.Mixin,{_instantiateReactComponent:a}),e.exports=a}).call(t,n(5))},function(e,t,n){(function(t){"use strict";function r(e){var t=e._currentElement._owner||null;if(t){var n=t.getName();if(n)return" Check the render method of `"+n+"`."}return""}function o(e){}var a=n(65),i=n(6),u=n(43),s=n(48),l=n(19),c=n(66),p=n(67),d=n(51),f=n(54),h=n(40),v=n(59),m=n(14),y=n(68),g=n(26);o.prototype.render=function(){var e=s.get(this)._currentElement.type;return e(this.props,this.context,this.updater)};var b=1,_={construct:function(e){this._currentElement=e,this._rootNodeID=null,this._instance=null,this._pendingElement=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._renderedComponent=null,this._context=null,this._mountOrder=0,this._topLevelWrapper=null,this._pendingCallbacks=null},mountComponent:function(e,n,r){this._context=r,this._mountOrder=b++,this._rootNodeID=e;var a,l,c=this._processProps(this._currentElement.props),p=this._processContext(r),h=this._currentElement.type,y="prototype"in h;if(y)if("production"!==t.env.NODE_ENV){i.current=this;try{a=new h(c,p,f)}finally{i.current=null}}else a=new h(c,p,f);y&&null!==a&&a!==!1&&!u.isValidElement(a)||(l=a,a=new o(h)),"production"!==t.env.NODE_ENV&&(null==a.render?"production"!==t.env.NODE_ENV?g(!1,"%s(...): No `render` method found on the returned component instance: you may have forgotten to define `render`, returned null/false from a stateless component, or tried to render an element whose type is a function that isn't a React component.",h.displayName||h.name||"Component"):void 0:"production"!==t.env.NODE_ENV?g(h.prototype&&h.prototype.isReactComponent||!y||!(a instanceof h),"%s(...): React component classes must extend React.Component.",h.displayName||h.name||"Component"):void 0),a.props=c,a.context=p,a.refs=v,a.updater=f,this._instance=a,s.set(a,this),"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?g(!a.getInitialState||a.getInitialState.isReactClassApproved,"getInitialState was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?",this.getName()||"a component"):void 0,"production"!==t.env.NODE_ENV?g(!a.getDefaultProps||a.getDefaultProps.isReactClassApproved,"getDefaultProps was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Use a static property to define defaultProps instead.",this.getName()||"a component"):void 0,"production"!==t.env.NODE_ENV?g(!a.propTypes,"propTypes was defined as an instance property on %s. Use a static property to define propTypes instead.",this.getName()||"a component"):void 0,"production"!==t.env.NODE_ENV?g(!a.contextTypes,"contextTypes was defined as an instance property on %s. Use a static property to define contextTypes instead.",this.getName()||"a component"):void 0,"production"!==t.env.NODE_ENV?g("function"!=typeof a.componentShouldUpdate,"%s has a method called componentShouldUpdate(). Did you mean shouldComponentUpdate()? The name is phrased as a question because the function is expected to return a value.",this.getName()||"A component"):void 0,"production"!==t.env.NODE_ENV?g("function"!=typeof a.componentDidUnmount,"%s has a method called componentDidUnmount(). But there is no such lifecycle method. Did you mean componentWillUnmount()?",this.getName()||"A component"):void 0,"production"!==t.env.NODE_ENV?g("function"!=typeof a.componentWillRecieveProps,"%s has a method called componentWillRecieveProps(). Did you mean componentWillReceiveProps()?",this.getName()||"A component"):void 0);var _=a.state;void 0===_&&(a.state=_=null),"object"!=typeof _||Array.isArray(_)?"production"!==t.env.NODE_ENV?m(!1,"%s.state: must be set to an object or null",this.getName()||"ReactCompositeComponent"):m(!1):void 0,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,a.componentWillMount&&(a.componentWillMount(),this._pendingStateQueue&&(a.state=this._processPendingState(a.props,a.context))),void 0===l&&(l=this._renderValidatedComponent()),this._renderedComponent=this._instantiateReactComponent(l);var E=d.mountComponent(this._renderedComponent,e,n,this._processChildContext(r));return a.componentDidMount&&n.getReactMountReady().enqueue(a.componentDidMount,a),E},unmountComponent:function(){var e=this._instance;e.componentWillUnmount&&e.componentWillUnmount(),d.unmountComponent(this._renderedComponent),this._renderedComponent=null,this._instance=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._pendingCallbacks=null,this._pendingElement=null,this._context=null,this._rootNodeID=null,this._topLevelWrapper=null,s.remove(e)},_maskContext:function(e){var t=null,n=this._currentElement.type,r=n.contextTypes;if(!r)return v;t={};for(var o in r)t[o]=e[o];return t},_processContext:function(e){var n=this._maskContext(e);if("production"!==t.env.NODE_ENV){var r=this._currentElement.type;r.contextTypes&&this._checkPropTypes(r.contextTypes,n,c.context)}return n},_processChildContext:function(e){var n=this._currentElement.type,r=this._instance,o=r.getChildContext&&r.getChildContext();if(o){"object"!=typeof n.childContextTypes?"production"!==t.env.NODE_ENV?m(!1,"%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().",this.getName()||"ReactCompositeComponent"):m(!1):void 0,"production"!==t.env.NODE_ENV&&this._checkPropTypes(n.childContextTypes,o,c.childContext);for(var a in o)a in n.childContextTypes?void 0:"production"!==t.env.NODE_ENV?m(!1,'%s.getChildContext(): key "%s" is not defined in childContextTypes.',this.getName()||"ReactCompositeComponent",a):m(!1);return h({},e,o)}return e},_processProps:function(e){if("production"!==t.env.NODE_ENV){var n=this._currentElement.type;n.propTypes&&this._checkPropTypes(n.propTypes,e,c.prop)}return e},_checkPropTypes:function(e,n,o){var a=this.getName();for(var i in e)if(e.hasOwnProperty(i)){var u;try{"function"!=typeof e[i]?"production"!==t.env.NODE_ENV?m(!1,"%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.",a||"React class",p[o],i):m(!1):void 0,u=e[i](n,i,a,o)}catch(s){u=s}if(u instanceof Error){var l=r(this);o===c.prop?"production"!==t.env.NODE_ENV?g(!1,"Failed Composite propType: %s%s",u.message,l):void 0:"production"!==t.env.NODE_ENV?g(!1,"Failed Context Types: %s%s",u.message,l):void 0}}},receiveComponent:function(e,t,n){var r=this._currentElement,o=this._context;this._pendingElement=null,this.updateComponent(t,r,e,o,n)},performUpdateIfNecessary:function(e){null!=this._pendingElement&&d.receiveComponent(this,this._pendingElement||this._currentElement,e,this._context),(null!==this._pendingStateQueue||this._pendingForceUpdate)&&this.updateComponent(e,this._currentElement,this._currentElement,this._context,this._context)},updateComponent:function(e,n,r,o,a){var i,u=this._instance,s=this._context===a?u.context:this._processContext(a);n===r?i=r.props:(i=this._processProps(r.props),u.componentWillReceiveProps&&u.componentWillReceiveProps(i,s));var l=this._processPendingState(i,s),c=this._pendingForceUpdate||!u.shouldComponentUpdate||u.shouldComponentUpdate(i,l,s);"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?g("undefined"!=typeof c,"%s.shouldComponentUpdate(): Returned undefined instead of a boolean value. Make sure to return true or false.",this.getName()||"ReactCompositeComponent"):void 0),c?(this._pendingForceUpdate=!1,this._performComponentUpdate(r,i,l,s,e,a)):(this._currentElement=r,this._context=a,u.props=i,u.state=l,u.context=s)},_processPendingState:function(e,t){var n=this._instance,r=this._pendingStateQueue,o=this._pendingReplaceState;if(this._pendingReplaceState=!1,this._pendingStateQueue=null,!r)return n.state;if(o&&1===r.length)return r[0];for(var a=h({},o?r[0]:n.state),i=o?1:0;i<r.length;i++){var u=r[i];h(a,"function"==typeof u?u.call(n,a,e,t):u)}return a},_performComponentUpdate:function(e,t,n,r,o,a){var i,u,s,l=this._instance,c=Boolean(l.componentDidUpdate);c&&(i=l.props,u=l.state,s=l.context),l.componentWillUpdate&&l.componentWillUpdate(t,n,r),this._currentElement=e,this._context=a,l.props=t,l.state=n,l.context=r,this._updateRenderedComponent(o,a),c&&o.getReactMountReady().enqueue(l.componentDidUpdate.bind(l,i,u,s),l)},_updateRenderedComponent:function(e,t){var n=this._renderedComponent,r=n._currentElement,o=this._renderValidatedComponent();if(y(r,o))d.receiveComponent(n,o,e,this._processChildContext(t));else{var a=this._rootNodeID,i=n._rootNodeID;d.unmountComponent(n),this._renderedComponent=this._instantiateReactComponent(o);var u=d.mountComponent(this._renderedComponent,a,e,this._processChildContext(t));this._replaceNodeWithMarkupByID(i,u)}},_replaceNodeWithMarkupByID:function(e,t){a.replaceNodeWithMarkupByID(e,t)},_renderValidatedComponentWithoutOwnerOrContext:function(){var e=this._instance,n=e.render();return"production"!==t.env.NODE_ENV&&"undefined"==typeof n&&e.render._isMockFunction&&(n=null),n},_renderValidatedComponent:function(){var e;i.current=this;try{e=this._renderValidatedComponentWithoutOwnerOrContext()}finally{i.current=null}return null===e||e===!1||u.isValidElement(e)?void 0:"production"!==t.env.NODE_ENV?m(!1,"%s.render(): A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object.",this.getName()||"ReactCompositeComponent"):m(!1),e},attachRef:function(e,n){var r=this.getPublicInstance();null==r?"production"!==t.env.NODE_ENV?m(!1,"Stateless function components cannot have refs."):m(!1):void 0;var o=n.getPublicInstance();if("production"!==t.env.NODE_ENV){var a=n&&n.getName?n.getName():"a component";"production"!==t.env.NODE_ENV?g(null!=o,'Stateless function components cannot be given refs (See ref "%s" in %s created by %s). Attempts to access this ref will fail.',e,a,this.getName()):void 0}var i=r.refs===v?r.refs={}:r.refs;i[e]=o},detachRef:function(e){var t=this.getPublicInstance().refs;delete t[e]},getName:function(){var e=this._currentElement.type,t=this._instance&&this._instance.constructor;return e.displayName||t&&t.displayName||e.name||t&&t.name||null},getPublicInstance:function(){var e=this._instance;return e instanceof o?null:e},_instantiateReactComponent:null};l.measureMethods(_,"ReactCompositeComponent",{mountComponent:"mountComponent",updateComponent:"updateComponent",_renderValidatedComponent:"_renderValidatedComponent"});var E={Mixin:_};e.exports=E}).call(t,n(5))},function(e,t,n){(function(t){"use strict";var r=n(14),o=!1,a={unmountIDFromEnvironment:null,replaceNodeWithMarkupByID:null,processChildrenUpdates:null,injection:{injectEnvironment:function(e){o?"production"!==t.env.NODE_ENV?r(!1,"ReactCompositeComponent: injectEnvironment() can only be called once."):r(!1):void 0,a.unmountIDFromEnvironment=e.unmountIDFromEnvironment,a.replaceNodeWithMarkupByID=e.replaceNodeWithMarkupByID,a.processChildrenUpdates=e.processChildrenUpdates,o=!0}}};e.exports=a}).call(t,n(5))},function(e,t,n){"use strict";var r=n(18),o=r({ prop:null,context:null,childContext:null});e.exports=o},function(e,t,n){(function(t){"use strict";var n={};"production"!==t.env.NODE_ENV&&(n={prop:"prop",context:"context",childContext:"child context"}),e.exports=n}).call(t,n(5))},function(e,t){"use strict";function n(e,t){var n=null===e||e===!1,r=null===t||t===!1;if(n||r)return n===r;var o=typeof e,a=typeof t;return"string"===o||"number"===o?"string"===a||"number"===a:"object"===a&&e.type===t.type&&e.key===t.key}e.exports=n},function(e,t,n){"use strict";function r(){i.registerNullComponentID(this._rootNodeID)}var o,a=n(43),i=n(45),u=n(51),s=n(40),l={injectEmptyComponent:function(e){o=a.createElement(e)}},c=function(e){this._currentElement=null,this._rootNodeID=null,this._renderedComponent=e(o)};s(c.prototype,{construct:function(e){},mountComponent:function(e,t,n){return t.getReactMountReady().enqueue(r,this),this._rootNodeID=e,u.mountComponent(this._renderedComponent,e,t,n)},receiveComponent:function(){},unmountComponent:function(e,t,n){u.unmountComponent(this._renderedComponent),i.deregisterNullComponentID(this._rootNodeID),this._rootNodeID=null,this._renderedComponent=null}}),c.injection=l,e.exports=c},function(e,t,n){(function(t){"use strict";function r(e){if("function"==typeof e.type)return e.type;var t=e.type,n=p[t];return null==n&&(p[t]=n=l(t)),n}function o(e){return c?void 0:"production"!==t.env.NODE_ENV?s(!1,"There is no registered component for the tag %s",e.type):s(!1),new c(e.type,e.props)}function a(e){return new d(e)}function i(e){return e instanceof d}var u=n(40),s=n(14),l=null,c=null,p={},d=null,f={injectGenericComponentClass:function(e){c=e},injectTextComponentClass:function(e){d=e},injectComponentClasses:function(e){u(p,e)}},h={getComponentClassForElement:r,createInternalComponent:o,createInstanceForText:a,isTextComponent:i,injection:f};e.exports=h}).call(t,n(5))},function(e,t,n){(function(t){"use strict";var r=n(40),o=n(16),a=n(26),i=o;if("production"!==t.env.NODE_ENV){var u=["address","applet","area","article","aside","base","basefont","bgsound","blockquote","body","br","button","caption","center","col","colgroup","dd","details","dir","div","dl","dt","embed","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","iframe","img","input","isindex","li","link","listing","main","marquee","menu","menuitem","meta","nav","noembed","noframes","noscript","object","ol","p","param","plaintext","pre","script","section","select","source","style","summary","table","tbody","td","template","textarea","tfoot","th","thead","title","tr","track","ul","wbr","xmp"],s=["applet","caption","html","table","td","th","marquee","object","template","foreignObject","desc","title"],l=s.concat(["button"]),c=["dd","dt","li","option","optgroup","p","rp","rt"],p={parentTag:null,formTag:null,aTagInScope:null,buttonTagInScope:null,nobrTagInScope:null,pTagInButtonScope:null,listItemTagAutoclosing:null,dlItemTagAutoclosing:null},d=function(e,t,n){var o=r({},e||p),a={tag:t,instance:n};return-1!==s.indexOf(t)&&(o.aTagInScope=null,o.buttonTagInScope=null,o.nobrTagInScope=null),-1!==l.indexOf(t)&&(o.pTagInButtonScope=null),-1!==u.indexOf(t)&&"address"!==t&&"div"!==t&&"p"!==t&&(o.listItemTagAutoclosing=null,o.dlItemTagAutoclosing=null),o.parentTag=a,"form"===t&&(o.formTag=a),"a"===t&&(o.aTagInScope=a),"button"===t&&(o.buttonTagInScope=a),"nobr"===t&&(o.nobrTagInScope=a),"p"===t&&(o.pTagInButtonScope=a),"li"===t&&(o.listItemTagAutoclosing=a),"dd"!==t&&"dt"!==t||(o.dlItemTagAutoclosing=a),o},f=function(e,t){switch(t){case"select":return"option"===e||"optgroup"===e||"#text"===e;case"optgroup":return"option"===e||"#text"===e;case"option":return"#text"===e;case"tr":return"th"===e||"td"===e||"style"===e||"script"===e||"template"===e;case"tbody":case"thead":case"tfoot":return"tr"===e||"style"===e||"script"===e||"template"===e;case"colgroup":return"col"===e||"template"===e;case"table":return"caption"===e||"colgroup"===e||"tbody"===e||"tfoot"===e||"thead"===e||"style"===e||"script"===e||"template"===e;case"head":return"base"===e||"basefont"===e||"bgsound"===e||"link"===e||"meta"===e||"title"===e||"noscript"===e||"noframes"===e||"style"===e||"script"===e||"template"===e;case"html":return"head"===e||"body"===e}switch(e){case"h1":case"h2":case"h3":case"h4":case"h5":case"h6":return"h1"!==t&&"h2"!==t&&"h3"!==t&&"h4"!==t&&"h5"!==t&&"h6"!==t;case"rp":case"rt":return-1===c.indexOf(t);case"caption":case"col":case"colgroup":case"frame":case"head":case"tbody":case"td":case"tfoot":case"th":case"thead":case"tr":return null==t}return!0},h=function(e,t){switch(e){case"address":case"article":case"aside":case"blockquote":case"center":case"details":case"dialog":case"dir":case"div":case"dl":case"fieldset":case"figcaption":case"figure":case"footer":case"header":case"hgroup":case"main":case"menu":case"nav":case"ol":case"p":case"section":case"summary":case"ul":case"pre":case"listing":case"table":case"hr":case"xmp":case"h1":case"h2":case"h3":case"h4":case"h5":case"h6":return t.pTagInButtonScope;case"form":return t.formTag||t.pTagInButtonScope;case"li":return t.listItemTagAutoclosing;case"dd":case"dt":return t.dlItemTagAutoclosing;case"button":return t.buttonTagInScope;case"a":return t.aTagInScope;case"nobr":return t.nobrTagInScope}return null},v=function(e){if(!e)return[];var t=[];do t.push(e);while(e=e._currentElement._owner);return t.reverse(),t},m={};i=function(e,n,r){r=r||p;var o=r.parentTag,i=o&&o.tag,u=f(e,i)?null:o,s=u?null:h(e,r),l=u||s;if(l){var c,d=l.tag,y=l.instance,g=n&&n._currentElement._owner,b=y&&y._currentElement._owner,_=v(g),E=v(b),N=Math.min(_.length,E.length),O=-1;for(c=0;N>c&&_[c]===E[c];c++)O=c;var C="(unknown)",P=_.slice(O+1).map(function(e){return e.getName()||C}),w=E.slice(O+1).map(function(e){return e.getName()||C}),T=[].concat(-1!==O?_[O].getName()||C:[],w,d,s?["..."]:[],P,e).join(" > "),x=!!u+"|"+e+"|"+d+"|"+T;if(m[x])return;if(m[x]=!0,u){var D="";"table"===d&&"tr"===e&&(D+=" Add a <tbody> to your code to match the DOM tree generated by the browser."),"production"!==t.env.NODE_ENV?a(!1,"validateDOMNesting(...): <%s> cannot appear as a child of <%s>. See %s.%s",e,d,T,D):void 0}else"production"!==t.env.NODE_ENV?a(!1,"validateDOMNesting(...): <%s> cannot appear as a descendant of <%s>. See %s.",e,d,T):void 0}},i.ancestorInfoContextKey="__validateDOMNesting_ancestorInfo$"+Math.random().toString(36).slice(2),i.updatedAncestorInfo=d,i.isTagValidInContext=function(e,t){t=t||p;var n=t.parentTag,r=n&&n.tag;return f(e,r)&&!h(e,t)}}e.exports=i}).call(t,n(5))},function(e,t,n){(function(t){"use strict";function r(){if(!P&&(P=!0,y.EventEmitter.injectReactEventListener(m),y.EventPluginHub.injectEventPluginOrder(u),y.EventPluginHub.injectInstanceHandle(g),y.EventPluginHub.injectMount(b),y.EventPluginHub.injectEventPluginsByName({SimpleEventPlugin:O,EnterLeaveEventPlugin:s,ChangeEventPlugin:a,SelectEventPlugin:E,BeforeInputEventPlugin:o}),y.NativeComponent.injectGenericComponentClass(h),y.NativeComponent.injectTextComponentClass(v),y.Class.injectMixin(p),y.DOMProperty.injectDOMPropertyConfig(c),y.DOMProperty.injectDOMPropertyConfig(C),y.EmptyComponent.injectEmptyComponent("noscript"),y.Updates.injectReconcileTransaction(_),y.Updates.injectBatchingStrategy(f),y.RootIndex.injectCreateReactRootIndex(l.canUseDOM?i.createReactRootIndex:N.createReactRootIndex),y.Component.injectEnvironment(d),"production"!==t.env.NODE_ENV)){var e=l.canUseDOM&&window.location.href||"";if(/[?&]react_perf\b/.test(e)){var r=n(143);r.start()}}}var o=n(73),a=n(81),i=n(84),u=n(85),s=n(86),l=n(10),c=n(90),p=n(91),d=n(27),f=n(93),h=n(94),v=n(7),m=n(119),y=n(122),g=n(46),b=n(29),_=n(126),E=n(131),N=n(132),O=n(133),C=n(142),P=!1;e.exports={inject:r}}).call(t,n(5))},function(e,t,n){"use strict";function r(){var e=window.opera;return"object"==typeof e&&"function"==typeof e.version&&parseInt(e.version(),10)<=12}function o(e){return(e.ctrlKey||e.altKey||e.metaKey)&&!(e.ctrlKey&&e.altKey)}function a(e){switch(e){case x.topCompositionStart:return D.compositionStart;case x.topCompositionEnd:return D.compositionEnd;case x.topCompositionUpdate:return D.compositionUpdate}}function i(e,t){return e===x.topKeyDown&&t.keyCode===E}function u(e,t){switch(e){case x.topKeyUp:return-1!==_.indexOf(t.keyCode);case x.topKeyDown:return t.keyCode!==E;case x.topKeyPress:case x.topMouseDown:case x.topBlur:return!0;default:return!1}}function s(e){var t=e.detail;return"object"==typeof t&&"data"in t?t.data:null}function l(e,t,n,r,o){var l,c;if(N?l=a(e):k?u(e,r)&&(l=D.compositionEnd):i(e,r)&&(l=D.compositionStart),!l)return null;P&&(k||l!==D.compositionStart?l===D.compositionEnd&&k&&(c=k.getData()):k=m.getPooled(t));var p=y.getPooled(l,n,r,o);if(c)p.data=c;else{var d=s(r);null!==d&&(p.data=d)}return h.accumulateTwoPhaseDispatches(p),p}function c(e,t){switch(e){case x.topCompositionEnd:return s(t);case x.topKeyPress:var n=t.which;return n!==w?null:(M=!0,T);case x.topTextInput:var r=t.data;return r===T&&M?null:r;default:return null}}function p(e,t){if(k){if(e===x.topCompositionEnd||u(e,t)){var n=k.getData();return m.release(k),k=null,n}return null}switch(e){case x.topPaste:return null;case x.topKeyPress:return t.which&&!o(t)?String.fromCharCode(t.which):null;case x.topCompositionEnd:return P?null:t.data;default:return null}}function d(e,t,n,r,o){var a;if(a=C?c(e,r):p(e,r),!a)return null;var i=g.getPooled(D.beforeInput,n,r,o);return i.data=a,h.accumulateTwoPhaseDispatches(i),i}var f=n(31),h=n(74),v=n(10),m=n(75),y=n(77),g=n(79),b=n(80),_=[9,13,27,32],E=229,N=v.canUseDOM&&"CompositionEvent"in window,O=null;v.canUseDOM&&"documentMode"in document&&(O=document.documentMode);var C=v.canUseDOM&&"TextEvent"in window&&!O&&!r(),P=v.canUseDOM&&(!N||O&&O>8&&11>=O),w=32,T=String.fromCharCode(w),x=f.topLevelTypes,D={beforeInput:{phasedRegistrationNames:{bubbled:b({onBeforeInput:null}),captured:b({onBeforeInputCapture:null})},dependencies:[x.topCompositionEnd,x.topKeyPress,x.topTextInput,x.topPaste]},compositionEnd:{phasedRegistrationNames:{bubbled:b({onCompositionEnd:null}),captured:b({onCompositionEndCapture:null})},dependencies:[x.topBlur,x.topCompositionEnd,x.topKeyDown,x.topKeyPress,x.topKeyUp,x.topMouseDown]},compositionStart:{phasedRegistrationNames:{bubbled:b({onCompositionStart:null}),captured:b({onCompositionStartCapture:null})},dependencies:[x.topBlur,x.topCompositionStart,x.topKeyDown,x.topKeyPress,x.topKeyUp,x.topMouseDown]},compositionUpdate:{phasedRegistrationNames:{bubbled:b({onCompositionUpdate:null}),captured:b({onCompositionUpdateCapture:null})},dependencies:[x.topBlur,x.topCompositionUpdate,x.topKeyDown,x.topKeyPress,x.topKeyUp,x.topMouseDown]}},M=!1,k=null,S={eventTypes:D,extractEvents:function(e,t,n,r,o){return[l(e,t,n,r,o),d(e,t,n,r,o)]}};e.exports=S},function(e,t,n){(function(t){"use strict";function r(e,t,n){var r=t.dispatchConfig.phasedRegistrationNames[n];return b(e,r)}function o(e,n,o){"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?v(e,"Dispatching id must not be null"):void 0);var a=n?g.bubbled:g.captured,i=r(e,o,a);i&&(o._dispatchListeners=m(o._dispatchListeners,i),o._dispatchIDs=m(o._dispatchIDs,e))}function a(e){e&&e.dispatchConfig.phasedRegistrationNames&&h.injection.getInstanceHandle().traverseTwoPhase(e.dispatchMarker,o,e)}function i(e){e&&e.dispatchConfig.phasedRegistrationNames&&h.injection.getInstanceHandle().traverseTwoPhaseSkipTarget(e.dispatchMarker,o,e)}function u(e,t,n){if(n&&n.dispatchConfig.registrationName){var r=n.dispatchConfig.registrationName,o=b(e,r);o&&(n._dispatchListeners=m(n._dispatchListeners,o),n._dispatchIDs=m(n._dispatchIDs,e))}}function s(e){e&&e.dispatchConfig.registrationName&&u(e.dispatchMarker,null,e)}function l(e){y(e,a)}function c(e){y(e,i)}function p(e,t,n,r){h.injection.getInstanceHandle().traverseEnterLeave(n,r,u,e,t)}function d(e){y(e,s)}var f=n(31),h=n(32),v=n(26),m=n(36),y=n(37),g=f.PropagationPhases,b=h.getListener,_={accumulateTwoPhaseDispatches:l,accumulateTwoPhaseDispatchesSkipTarget:c,accumulateDirectDispatches:d,accumulateEnterLeaveDispatches:p};e.exports=_}).call(t,n(5))},function(e,t,n){"use strict";function r(e){this._root=e,this._startText=this.getText(),this._fallbackText=null}var o=n(57),a=n(40),i=n(76);a(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[i()]},getData:function(){if(this._fallbackText)return this._fallbackText;var e,t,n=this._startText,r=n.length,o=this.getText(),a=o.length;for(e=0;r>e&&n[e]===o[e];e++);var i=r-e;for(t=1;i>=t&&n[r-t]===o[a-t];t++);var u=t>1?1-t:void 0;return this._fallbackText=o.slice(e,u),this._fallbackText}}),o.addPoolingTo(r),e.exports=r},function(e,t,n){"use strict";function r(){return!a&&o.canUseDOM&&(a="textContent"in document.documentElement?"textContent":"innerText"),a}var o=n(10),a=null;e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(78),a={data:null};o.augmentClass(r,a),e.exports=r},function(e,t,n){(function(t){"use strict";function r(e,t,n,r){this.dispatchConfig=e,this.dispatchMarker=t,this.nativeEvent=n;var o=this.constructor.Interface;for(var a in o)if(o.hasOwnProperty(a)){var u=o[a];u?this[a]=u(n):"target"===a?this.target=r:this[a]=n[a]}var s=null!=n.defaultPrevented?n.defaultPrevented:n.returnValue===!1;s?this.isDefaultPrevented=i.thatReturnsTrue:this.isDefaultPrevented=i.thatReturnsFalse,this.isPropagationStopped=i.thatReturnsFalse}var o=n(57),a=n(40),i=n(16),u=n(26),s={type:null,target:null,currentTarget:i.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null};a(r.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?u(e,"This synthetic event is reused for performance reasons. If you're seeing this, you're calling `preventDefault` on a released/nullified synthetic event. This is a no-op. See https://fb.me/react-event-pooling for more information."):void 0),e&&(e.preventDefault?e.preventDefault():e.returnValue=!1,this.isDefaultPrevented=i.thatReturnsTrue)},stopPropagation:function(){var e=this.nativeEvent;"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?u(e,"This synthetic event is reused for performance reasons. If you're seeing this, you're calling `stopPropagation` on a released/nullified synthetic event. This is a no-op. See https://fb.me/react-event-pooling for more information."):void 0),e&&(e.stopPropagation?e.stopPropagation():e.cancelBubble=!0,this.isPropagationStopped=i.thatReturnsTrue)},persist:function(){this.isPersistent=i.thatReturnsTrue},isPersistent:i.thatReturnsFalse,destructor:function(){var e=this.constructor.Interface;for(var t in e)this[t]=null;this.dispatchConfig=null,this.dispatchMarker=null,this.nativeEvent=null}}),r.Interface=s,r.augmentClass=function(e,t){var n=this,r=Object.create(n.prototype);a(r,e.prototype),e.prototype=r,e.prototype.constructor=e,e.Interface=a({},n.Interface,t),e.augmentClass=n.augmentClass,o.addPoolingTo(e,o.fourArgumentPooler)},o.addPoolingTo(r,o.fourArgumentPooler),e.exports=r}).call(t,n(5))},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(78),a={data:null};o.augmentClass(r,a),e.exports=r},function(e,t){"use strict";var n=function(e){var t;for(t in e)if(e.hasOwnProperty(t))return t;return null};e.exports=n},function(e,t,n){"use strict";function r(e){var t=e.nodeName&&e.nodeName.toLowerCase();return"select"===t||"input"===t&&"file"===e.type}function o(e){var t=O.getPooled(D.change,k,e,C(e));_.accumulateTwoPhaseDispatches(t),N.batchedUpdates(a,t)}function a(e){b.enqueueEvents(e),b.processEventQueue(!1)}function i(e,t){M=e,k=t,M.attachEvent("onchange",o)}function u(){M&&(M.detachEvent("onchange",o),M=null,k=null)}function s(e,t,n){return e===x.topChange?n:void 0}function l(e,t,n){e===x.topFocus?(u(),i(t,n)):e===x.topBlur&&u()}function c(e,t){M=e,k=t,S=e.value,R=Object.getOwnPropertyDescriptor(e.constructor.prototype,"value"),Object.defineProperty(M,"value",A),M.attachEvent("onpropertychange",d)}function p(){M&&(delete M.value,M.detachEvent("onpropertychange",d),M=null,k=null,S=null,R=null)}function d(e){if("value"===e.propertyName){var t=e.srcElement.value;t!==S&&(S=t,o(e))}}function f(e,t,n){return e===x.topInput?n:void 0}function h(e,t,n){e===x.topFocus?(p(),c(t,n)):e===x.topBlur&&p()}function v(e,t,n){return e!==x.topSelectionChange&&e!==x.topKeyUp&&e!==x.topKeyDown||!M||M.value===S?void 0:(S=M.value,k)}function m(e){return e.nodeName&&"input"===e.nodeName.toLowerCase()&&("checkbox"===e.type||"radio"===e.type)}function y(e,t,n){return e===x.topClick?n:void 0}var g=n(31),b=n(32),_=n(74),E=n(10),N=n(55),O=n(78),C=n(82),P=n(41),w=n(83),T=n(80),x=g.topLevelTypes,D={change:{phasedRegistrationNames:{bubbled:T({onChange:null}),captured:T({onChangeCapture:null})},dependencies:[x.topBlur,x.topChange,x.topClick,x.topFocus,x.topInput,x.topKeyDown,x.topKeyUp,x.topSelectionChange]}},M=null,k=null,S=null,R=null,I=!1;E.canUseDOM&&(I=P("change")&&(!("documentMode"in document)||document.documentMode>8));var j=!1;E.canUseDOM&&(j=P("input")&&(!("documentMode"in document)||document.documentMode>9));var A={get:function(){return R.get.call(this)},set:function(e){S=""+e,R.set.call(this,e)}},V={eventTypes:D,extractEvents:function(e,t,n,o,a){var i,u;if(r(t)?I?i=s:u=l:w(t)?j?i=f:(i=v,u=h):m(t)&&(i=y),i){var c=i(e,t,n);if(c){var p=O.getPooled(D.change,c,o,a);return p.type="change",_.accumulateTwoPhaseDispatches(p),p}}u&&u(e,t,n)}};e.exports=V},function(e,t){"use strict";function n(e){var t=e.target||e.srcElement||window;return 3===t.nodeType?t.parentNode:t}e.exports=n},function(e,t){"use strict";function n(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&r[e.type]||"textarea"===t)}var r={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};e.exports=n},function(e,t){"use strict";var n=0,r={createReactRootIndex:function(){return n++}};e.exports=r},function(e,t,n){"use strict";var r=n(80),o=[r({ResponderEventPlugin:null}),r({SimpleEventPlugin:null}),r({TapEventPlugin:null}),r({EnterLeaveEventPlugin:null}),r({ChangeEventPlugin:null}),r({SelectEventPlugin:null}),r({BeforeInputEventPlugin:null})];e.exports=o},function(e,t,n){"use strict";var r=n(31),o=n(74),a=n(87),i=n(29),u=n(80),s=r.topLevelTypes,l=i.getFirstReactDOM,c={mouseEnter:{registrationName:u({onMouseEnter:null}),dependencies:[s.topMouseOut,s.topMouseOver]},mouseLeave:{registrationName:u({onMouseLeave:null}),dependencies:[s.topMouseOut,s.topMouseOver]}},p=[null,null],d={eventTypes:c,extractEvents:function(e,t,n,r,u){if(e===s.topMouseOver&&(r.relatedTarget||r.fromElement))return null;if(e!==s.topMouseOut&&e!==s.topMouseOver)return null;var d;if(t.window===t)d=t;else{var f=t.ownerDocument;d=f?f.defaultView||f.parentWindow:window}var h,v,m="",y="";if(e===s.topMouseOut?(h=t,m=n,v=l(r.relatedTarget||r.toElement),v?y=i.getID(v):v=d,v=v||d):(h=d,v=t,y=n),h===v)return null;var g=a.getPooled(c.mouseLeave,m,r,u);g.type="mouseleave",g.target=h,g.relatedTarget=v;var b=a.getPooled(c.mouseEnter,y,r,u);return b.type="mouseenter",b.target=v,b.relatedTarget=h,o.accumulateEnterLeaveDispatches(g,b,m,y),p[0]=g,p[1]=b,p}};e.exports=d},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(88),a=n(39),i=n(89),u={screenX:null,screenY:null,clientX:null,clientY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:i,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+a.currentScrollLeft},pageY:function(e){return"pageY"in e?e.pageY:e.clientY+a.currentScrollTop}};o.augmentClass(r,u),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(78),a=n(82),i={view:function(e){if(e.view)return e.view;var t=a(e);if(null!=t&&t.window===t)return t;var n=t.ownerDocument;return n?n.defaultView||n.parentWindow:window},detail:function(e){return e.detail||0}};o.augmentClass(r,i),e.exports=r},function(e,t){"use strict";function n(e){var t=this,n=t.nativeEvent;if(n.getModifierState)return n.getModifierState(e);var r=o[e];return r?!!n[r]:!1}function r(e){return n}var o={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};e.exports=r},function(e,t,n){"use strict";var r,o=n(24),a=n(10),i=o.injection.MUST_USE_ATTRIBUTE,u=o.injection.MUST_USE_PROPERTY,s=o.injection.HAS_BOOLEAN_VALUE,l=o.injection.HAS_SIDE_EFFECTS,c=o.injection.HAS_NUMERIC_VALUE,p=o.injection.HAS_POSITIVE_NUMERIC_VALUE,d=o.injection.HAS_OVERLOADED_BOOLEAN_VALUE;if(a.canUseDOM){var f=document.implementation;r=f&&f.hasFeature&&f.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")}var h={isCustomAttribute:RegExp.prototype.test.bind(/^(data|aria)-[a-z_][a-z\d_.\-]*$/),Properties:{accept:null,acceptCharset:null,accessKey:null,action:null,allowFullScreen:i|s,allowTransparency:i,alt:null,async:s,autoComplete:null,autoPlay:s,capture:i|s,cellPadding:null,cellSpacing:null,charSet:i,challenge:i,checked:u|s,classID:i,className:r?i:u,cols:i|p,colSpan:null,content:null,contentEditable:null,contextMenu:i,controls:u|s,coords:null,crossOrigin:null,data:null,dateTime:i,"default":s,defer:s,dir:null,disabled:i|s,download:d,draggable:null,encType:null,form:i,formAction:i,formEncType:i,formMethod:i,formNoValidate:s,formTarget:i,frameBorder:i,headers:null,height:i,hidden:i|s,high:null,href:null,hrefLang:null,htmlFor:null,httpEquiv:null,icon:null,id:u,inputMode:i,integrity:null,is:i,keyParams:i,keyType:i,kind:null,label:null,lang:null,list:i,loop:u|s,low:null,manifest:i,marginHeight:null,marginWidth:null,max:null,maxLength:i,media:i,mediaGroup:null,method:null,min:null,minLength:i,multiple:u|s,muted:u|s,name:null,nonce:i,noValidate:s,open:s,optimum:null,pattern:null,placeholder:null,poster:null,preload:null,radioGroup:null,readOnly:u|s,rel:null,required:s,reversed:s,role:i,rows:i|p,rowSpan:null,sandbox:null,scope:null,scoped:s,scrolling:null,seamless:i|s,selected:u|s,shape:null,size:i|p,sizes:i,span:p,spellCheck:null,src:null,srcDoc:u,srcLang:null,srcSet:i,start:c,step:null,style:null,summary:null,tabIndex:null,target:null,title:null,type:null,useMap:null,value:u|l,width:i,wmode:i,wrap:null,about:i,datatype:i,inlist:i,prefix:i,property:i,resource:i,"typeof":i,vocab:i,autoCapitalize:i,autoCorrect:i,autoSave:null,color:null,itemProp:i,itemScope:i|s,itemType:i,itemID:i,itemRef:i,results:null,security:i,unselectable:i},DOMAttributeNames:{acceptCharset:"accept-charset",className:"class",htmlFor:"for",httpEquiv:"http-equiv"},DOMPropertyNames:{autoComplete:"autocomplete",autoFocus:"autofocus",autoPlay:"autoplay",autoSave:"autosave",encType:"encoding",hrefLang:"hreflang",radioGroup:"radiogroup",spellCheck:"spellcheck",srcDoc:"srcdoc",srcSet:"srcset"}};e.exports=h},function(e,t,n){(function(t){"use strict";var r=n(48),o=n(92),a=n(26),i="_getDOMNodeDidWarn",u={getDOMNode:function(){return"production"!==t.env.NODE_ENV?a(this.constructor[i],"%s.getDOMNode(...) is deprecated. Please use ReactDOM.findDOMNode(instance) instead.",r.get(this).getName()||this.tagName||"Unknown"):void 0,this.constructor[i]=!0,o(this)}};e.exports=u}).call(t,n(5))},function(e,t,n){(function(t){"use strict";function r(e){if("production"!==t.env.NODE_ENV){var n=o.current;null!==n&&("production"!==t.env.NODE_ENV?s(n._warnedAboutRefsInRender,"%s is accessing getDOMNode or findDOMNode inside its render(). render() should be a pure function of props and state. It should never access something that requires stale data from the previous render, such as refs. Move this logic to componentDidMount and componentDidUpdate instead.",n.getName()||"A component"):void 0,n._warnedAboutRefsInRender=!0)}return null==e?null:1===e.nodeType?e:a.has(e)?i.getNodeFromInstance(e):(null!=e.render&&"function"==typeof e.render?"production"!==t.env.NODE_ENV?u(!1,"findDOMNode was called on an unmounted component."):u(!1):void 0,void("production"!==t.env.NODE_ENV?u(!1,"Element appears to be neither ReactComponent nor DOMNode (keys: %s)",Object.keys(e)):u(!1)))}var o=n(6),a=n(48),i=n(29),u=n(14),s=n(26);e.exports=r}).call(t,n(5))},function(e,t,n){"use strict";function r(){this.reinitializeTransaction()}var o=n(55),a=n(58),i=n(40),u=n(16),s={initialize:u,close:function(){d.isBatchingUpdates=!1}},l={initialize:u,close:o.flushBatchedUpdates.bind(o)},c=[l,s];i(r.prototype,a.Mixin,{getTransactionWrappers:function(){return c}});var p=new r,d={isBatchingUpdates:!1,batchedUpdates:function(e,t,n,r,o,a){var i=d.isBatchingUpdates;d.isBatchingUpdates=!0,i?e(t,n,r,o,a):p.perform(e,null,t,n,r,o,a)}};e.exports=d},function(e,t,n){(function(t){"use strict";function r(e){if(e){var t=e._currentElement._owner||null;if(t){var n=t.getName();if(n)return" This DOM node was rendered by `"+n+"`."}}return""}function o(){if("production"!==t.env.NODE_ENV){var e=this._reactInternalComponent;"production"!==t.env.NODE_ENV?G(!1,"ReactDOMComponent: Do not access .getDOMNode() of a DOM node; instead, use the node directly.%s",r(e)):void 0}return this}function a(){var e=this._reactInternalComponent;return"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?G(!1,"ReactDOMComponent: Do not access .isMounted() of a DOM node.%s",r(e)):void 0),!!e}function i(){if("production"!==t.env.NODE_ENV){var e=this._reactInternalComponent;"production"!==t.env.NODE_ENV?G(!1,"ReactDOMComponent: Do not access .setState(), .replaceState(), or .forceUpdate() of a DOM node. This is a no-op.%s",r(e)):void 0}}function u(e,n){var o=this._reactInternalComponent;"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?G(!1,"ReactDOMComponent: Do not access .setProps() of a DOM node. Instead, call ReactDOM.render again at the top level.%s",r(o)):void 0),o&&(V.enqueueSetPropsInternal(o,e),n&&V.enqueueCallbackInternal(o,n))}function s(e,n){var o=this._reactInternalComponent;"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?G(!1,"ReactDOMComponent: Do not access .replaceProps() of a DOM node. Instead, call ReactDOM.render again at the top level.%s",r(o)):void 0),o&&(V.enqueueReplacePropsInternal(o,e),n&&V.enqueueCallbackInternal(o,n))}function l(e){if("object"==typeof e){if(Array.isArray(e))return"["+e.map(l).join(", ")+"]";var t=[];for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){var r=/^[a-z$_][\w$_]*$/i.test(n)?n:JSON.stringify(n);t.push(r+": "+l(e[n]))}return"{"+t.join(", ")+"}"}return"string"==typeof e?JSON.stringify(e):"function"==typeof e?"[function object]":String(e)}function c(e,n,r){if(null!=e&&null!=n&&!z(e,n)){var o,a=r._tag,i=r._currentElement._owner;i&&(o=i.getName());var u=o+"|"+a;re.hasOwnProperty(u)||(re[u]=!0,"production"!==t.env.NODE_ENV?G(!1,"`%s` was passed a style object that has previously been mutated. Mutating `style` is deprecated. Consider cloning it beforehand. Check the `render` %s. Previous style: %s. Mutated style: %s.",a,i?"of `"+o+"`":"using <"+a+">",l(e),l(n)):void 0)}}function p(e,n){n&&("production"!==t.env.NODE_ENV&&ue[e._tag]&&("production"!==t.env.NODE_ENV?G(null==n.children&&null==n.dangerouslySetInnerHTML,"%s is a void element tag and must not have `children` or use `props.dangerouslySetInnerHTML`.%s",e._tag,e._currentElement._owner?" Check the render method of "+e._currentElement._owner.getName()+".":""):void 0),null!=n.dangerouslySetInnerHTML&&(null!=n.children?"production"!==t.env.NODE_ENV?B(!1,"Can only set one of `children` or `props.dangerouslySetInnerHTML`."):B(!1):void 0,"object"==typeof n.dangerouslySetInnerHTML&&te in n.dangerouslySetInnerHTML?void 0:"production"!==t.env.NODE_ENV?B(!1,"`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information."):B(!1)),"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?G(null==n.innerHTML,"Directly setting property `innerHTML` is not permitted. For more information, lookup documentation on `dangerouslySetInnerHTML`."):void 0,"production"!==t.env.NODE_ENV?G(!n.contentEditable||null==n.children,"A component is `contentEditable` and contains `children` managed by React. It is now your responsibility to guarantee that none of those nodes are unexpectedly modified or duplicated. This is probably not intentional."):void 0),null!=n.style&&"object"!=typeof n.style?"production"!==t.env.NODE_ENV?B(!1,"The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX.%s",r(e)):B(!1):void 0)}function d(e,n,r,o){"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?G("onScroll"!==n||W("scroll",!0),"This browser doesn't support the `onScroll` event"):void 0);var a=I.findReactContainerForID(e);if(a){var i=a.nodeType===ne?a.ownerDocument:a;X(n,i)}o.getReactMountReady().enqueue(f,{id:e,registrationName:n,listener:r})}function f(){var e=this;T.putListener(e.id,e.registrationName,e.listener)}function h(){var e=this;e._rootNodeID?void 0:"production"!==t.env.NODE_ENV?B(!1,"Must be mounted to trap events"):B(!1);var n=I.getNode(e._rootNodeID);switch(n?void 0:"production"!==t.env.NODE_ENV?B(!1,"trapBubbledEvent(...): Requires node to be rendered."):B(!1),e._tag){case"iframe":e._wrapperState.listeners=[T.trapBubbledEvent(w.topLevelTypes.topLoad,"load",n)];break;case"video":case"audio":e._wrapperState.listeners=[];for(var r in oe)oe.hasOwnProperty(r)&&e._wrapperState.listeners.push(T.trapBubbledEvent(w.topLevelTypes[r],oe[r],n));break;case"img":e._wrapperState.listeners=[T.trapBubbledEvent(w.topLevelTypes.topError,"error",n),T.trapBubbledEvent(w.topLevelTypes.topLoad,"load",n)];break;case"form":e._wrapperState.listeners=[T.trapBubbledEvent(w.topLevelTypes.topReset,"reset",n),T.trapBubbledEvent(w.topLevelTypes.topSubmit,"submit",n)]}}function v(){M.mountReadyWrapper(this)}function m(){S.postUpdateWrapper(this)}function y(e){ce.call(le,e)||(se.test(e)?void 0:"production"!==t.env.NODE_ENV?B(!1,"Invalid tag: %s",e):B(!1),le[e]=!0)}function g(e,t){e=L({},e);var n=e[Y.ancestorInfoContextKey];return e[Y.ancestorInfoContextKey]=Y.updatedAncestorInfo(n,t._tag,t),e}function b(e,t){return e.indexOf("-")>=0||null!=t.is}function _(e){y(e),this._tag=e.toLowerCase(),this._renderedChildren=null,this._previousStyle=null,this._previousStyleCopy=null,this._rootNodeID=null,this._wrapperState=null,this._topLevelWrapper=null,this._nodeWithLegacyProperties=null,"production"!==t.env.NODE_ENV&&(this._unprocessedContextDev=null,this._processedContextDev=null)}var E,N=n(95),O=n(97),C=n(24),P=n(23),w=n(31),T=n(30),x=n(27),D=n(105),M=n(106),k=n(110),S=n(113),R=n(114),I=n(29),j=n(115),A=n(19),V=n(54),L=n(40),U=n(44),F=n(22),B=n(14),W=n(41),H=n(80),K=n(20),q=n(21),z=n(118),Y=n(71),G=n(26),$=T.deleteListener,X=T.listenTo,Q=T.registrationNameModules,Z={string:!0,number:!0},J=H({children:null}),ee=H({style:null}),te=H({__html:null}),ne=1;"production"!==t.env.NODE_ENV&&(E={props:{enumerable:!1,get:function(){var e=this._reactInternalComponent;return"production"!==t.env.NODE_ENV?G(!1,"ReactDOMComponent: Do not access .props of a DOM node; instead, recreate the props as `render` did originally or read the DOM properties/attributes directly from this node (e.g., this.refs.box.className).%s",r(e)):void 0,e._currentElement.props}}});var re={},oe={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"},ae={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},ie={listing:!0,pre:!0,textarea:!0},ue=L({menuitem:!0},ae),se=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,le={},ce={}.hasOwnProperty;_.displayName="ReactDOMComponent",_.Mixin={construct:function(e){this._currentElement=e},mountComponent:function(e,n,r){this._rootNodeID=e;var o=this._currentElement.props;switch(this._tag){case"iframe":case"img":case"form":case"video":case"audio":this._wrapperState={listeners:null},n.getReactMountReady().enqueue(h,this);break;case"button":o=D.getNativeProps(this,o,r);break;case"input":M.mountWrapper(this,o,r),o=M.getNativeProps(this,o,r);break;case"option":k.mountWrapper(this,o,r),o=k.getNativeProps(this,o,r);break;case"select":S.mountWrapper(this,o,r),o=S.getNativeProps(this,o,r),r=S.processChildContext(this,o,r);break;case"textarea":R.mountWrapper(this,o,r),o=R.getNativeProps(this,o,r)}p(this,o),"production"!==t.env.NODE_ENV&&r[Y.ancestorInfoContextKey]&&Y(this._tag,this,r[Y.ancestorInfoContextKey]),"production"!==t.env.NODE_ENV&&(this._unprocessedContextDev=r,this._processedContextDev=g(r,this),r=this._processedContextDev);var a;if(n.useCreateElement){var i=r[I.ownerDocumentContextKey],u=i.createElement(this._currentElement.type);P.setAttributeForID(u,this._rootNodeID),I.getID(u),this._updateDOMProperties({},o,n,u),this._createInitialChildren(n,o,r,u),a=u}else{var s=this._createOpenTagMarkupAndPutListeners(n,o),l=this._createContentMarkup(n,o,r);a=!l&&ae[this._tag]?s+"/>":s+">"+l+"</"+this._currentElement.type+">"}switch(this._tag){case"input":n.getReactMountReady().enqueue(v,this);case"button":case"select":case"textarea":o.autoFocus&&n.getReactMountReady().enqueue(N.focusDOMComponent,this)}return a},_createOpenTagMarkupAndPutListeners:function(e,n){var r="<"+this._currentElement.type;for(var o in n)if(n.hasOwnProperty(o)){var a=n[o];if(null!=a)if(Q.hasOwnProperty(o))a&&d(this._rootNodeID,o,a,e);else{o===ee&&(a&&("production"!==t.env.NODE_ENV&&(this._previousStyle=a),a=this._previousStyleCopy=L({},n.style)),a=O.createMarkupForStyles(a));var i=null;null!=this._tag&&b(this._tag,n)?o!==J&&(i=P.createMarkupForCustomAttribute(o,a)):i=P.createMarkupForProperty(o,a),i&&(r+=" "+i)}}if(e.renderToStaticMarkup)return r;var u=P.createMarkupForID(this._rootNodeID);return r+" "+u},_createContentMarkup:function(e,t,n){var r="",o=t.dangerouslySetInnerHTML;if(null!=o)null!=o.__html&&(r=o.__html);else{var a=Z[typeof t.children]?t.children:null,i=null!=a?null:t.children;if(null!=a)r=F(a);else if(null!=i){var u=this.mountChildren(i,e,n);r=u.join("")}}return ie[this._tag]&&"\n"===r.charAt(0)?"\n"+r:r},_createInitialChildren:function(e,t,n,r){var o=t.dangerouslySetInnerHTML;if(null!=o)null!=o.__html&&K(r,o.__html);else{var a=Z[typeof t.children]?t.children:null,i=null!=a?null:t.children;if(null!=a)q(r,a);else if(null!=i)for(var u=this.mountChildren(i,e,n),s=0;s<u.length;s++)r.appendChild(u[s])}},receiveComponent:function(e,t,n){var r=this._currentElement;this._currentElement=e,this.updateComponent(t,r,e,n)},updateComponent:function(e,n,r,o){var a=n.props,i=this._currentElement.props;switch(this._tag){case"button":a=D.getNativeProps(this,a),i=D.getNativeProps(this,i);break;case"input":M.updateWrapper(this),a=M.getNativeProps(this,a),i=M.getNativeProps(this,i);break;case"option":a=k.getNativeProps(this,a),i=k.getNativeProps(this,i);break;case"select":a=S.getNativeProps(this,a),i=S.getNativeProps(this,i);break;case"textarea":R.updateWrapper(this),a=R.getNativeProps(this,a),i=R.getNativeProps(this,i)}"production"!==t.env.NODE_ENV&&(this._unprocessedContextDev!==o&&(this._unprocessedContextDev=o,this._processedContextDev=g(o,this)),o=this._processedContextDev),p(this,i),this._updateDOMProperties(a,i,e,null),this._updateDOMChildren(a,i,e,o),!U&&this._nodeWithLegacyProperties&&(this._nodeWithLegacyProperties.props=i),"select"===this._tag&&e.getReactMountReady().enqueue(m,this)},_updateDOMProperties:function(e,n,r,o){var a,i,u;for(a in e)if(!n.hasOwnProperty(a)&&e.hasOwnProperty(a))if(a===ee){var s=this._previousStyleCopy;for(i in s)s.hasOwnProperty(i)&&(u=u||{},u[i]="");this._previousStyleCopy=null}else Q.hasOwnProperty(a)?e[a]&&$(this._rootNodeID,a):(C.properties[a]||C.isCustomAttribute(a))&&(o||(o=I.getNode(this._rootNodeID)),P.deleteValueForProperty(o,a));for(a in n){var l=n[a],p=a===ee?this._previousStyleCopy:e[a];if(n.hasOwnProperty(a)&&l!==p)if(a===ee)if(l?("production"!==t.env.NODE_ENV&&(c(this._previousStyleCopy,this._previousStyle,this),this._previousStyle=l),l=this._previousStyleCopy=L({},l)):this._previousStyleCopy=null,p){for(i in p)!p.hasOwnProperty(i)||l&&l.hasOwnProperty(i)||(u=u||{},u[i]="");for(i in l)l.hasOwnProperty(i)&&p[i]!==l[i]&&(u=u||{},u[i]=l[i])}else u=l;else Q.hasOwnProperty(a)?l?d(this._rootNodeID,a,l,r):p&&$(this._rootNodeID,a):b(this._tag,n)?(o||(o=I.getNode(this._rootNodeID)),a===J&&(l=null),P.setValueForAttribute(o,a,l)):(C.properties[a]||C.isCustomAttribute(a))&&(o||(o=I.getNode(this._rootNodeID)),null!=l?P.setValueForProperty(o,a,l):P.deleteValueForProperty(o,a))}u&&(o||(o=I.getNode(this._rootNodeID)),O.setValueForStyles(o,u))},_updateDOMChildren:function(e,t,n,r){var o=Z[typeof e.children]?e.children:null,a=Z[typeof t.children]?t.children:null,i=e.dangerouslySetInnerHTML&&e.dangerouslySetInnerHTML.__html,u=t.dangerouslySetInnerHTML&&t.dangerouslySetInnerHTML.__html,s=null!=o?null:e.children,l=null!=a?null:t.children,c=null!=o||null!=i,p=null!=a||null!=u;null!=s&&null==l?this.updateChildren(null,n,r):c&&!p&&this.updateTextContent(""),null!=a?o!==a&&this.updateTextContent(""+a):null!=u?i!==u&&this.updateMarkup(""+u):null!=l&&this.updateChildren(l,n,r)},unmountComponent:function(){switch(this._tag){case"iframe":case"img":case"form":case"video":case"audio":var e=this._wrapperState.listeners;if(e)for(var n=0;n<e.length;n++)e[n].remove();break;case"input":M.unmountWrapper(this);break;case"html":case"head":case"body":"production"!==t.env.NODE_ENV?B(!1,"<%s> tried to unmount. Because of cross-browser quirks it is impossible to unmount some top-level components (eg <html>, <head>, and <body>) reliably and efficiently. To fix this, have a single top-level component that never unmounts render these elements.",this._tag):B(!1)}if(this.unmountChildren(),T.deleteAllListeners(this._rootNodeID),x.unmountIDFromEnvironment(this._rootNodeID),this._rootNodeID=null,this._wrapperState=null,this._nodeWithLegacyProperties){var r=this._nodeWithLegacyProperties;r._reactInternalComponent=null,this._nodeWithLegacyProperties=null}},getPublicInstance:function(){if(!this._nodeWithLegacyProperties){var e=I.getNode(this._rootNodeID);e._reactInternalComponent=this,e.getDOMNode=o,e.isMounted=a,e.setState=i,e.replaceState=i,e.forceUpdate=i,e.setProps=u,e.replaceProps=s,"production"!==t.env.NODE_ENV&&U?Object.defineProperties(e,E):e.props=this._currentElement.props,this._nodeWithLegacyProperties=e}return this._nodeWithLegacyProperties}},A.measureMethods(_,"ReactDOMComponent",{mountComponent:"mountComponent",updateComponent:"updateComponent"}),L(_.prototype,_.Mixin,j.Mixin),e.exports=_}).call(t,n(5))},function(e,t,n){"use strict";var r=n(29),o=n(92),a=n(96),i={componentDidMount:function(){this.props.autoFocus&&a(o(this))}},u={Mixin:i,focusDOMComponent:function(){a(r.getNode(this._rootNodeID))}};e.exports=u},function(e,t){"use strict";function n(e){try{e.focus()}catch(t){}}e.exports=n},function(e,t,n){(function(t){"use strict";var r=n(98),o=n(10),a=n(19),i=n(99),u=n(101),s=n(102),l=n(104),c=n(26),p=l(function(e){return s(e)}),d=!1,f="cssFloat";if(o.canUseDOM){var h=document.createElement("div").style;try{h.font=""}catch(v){d=!0}void 0===document.documentElement.style.cssFloat&&(f="styleFloat")}if("production"!==t.env.NODE_ENV)var m=/^(?:webkit|moz|o)[A-Z]/,y=/;\s*$/,g={},b={},_=function(e){g.hasOwnProperty(e)&&g[e]||(g[e]=!0,"production"!==t.env.NODE_ENV?c(!1,"Unsupported style property %s. Did you mean %s?",e,i(e)):void 0)},E=function(e){g.hasOwnProperty(e)&&g[e]||(g[e]=!0,"production"!==t.env.NODE_ENV?c(!1,"Unsupported vendor-prefixed style property %s. Did you mean %s?",e,e.charAt(0).toUpperCase()+e.slice(1)):void 0)},N=function(e,n){b.hasOwnProperty(n)&&b[n]||(b[n]=!0,"production"!==t.env.NODE_ENV?c(!1,'Style property values shouldn\'t contain a semicolon. Try "%s: %s" instead.',e,n.replace(y,"")):void 0)},O=function(e,t){e.indexOf("-")>-1?_(e):m.test(e)?E(e):y.test(t)&&N(e,t)};var C={createMarkupForStyles:function(e){var n="";for(var r in e)if(e.hasOwnProperty(r)){var o=e[r];"production"!==t.env.NODE_ENV&&O(r,o),null!=o&&(n+=p(r)+":",n+=u(r,o)+";")}return n||null},setValueForStyles:function(e,n){var o=e.style;for(var a in n)if(n.hasOwnProperty(a)){"production"!==t.env.NODE_ENV&&O(a,n[a]);var i=u(a,n[a]);if("float"===a&&(a=f),i)o[a]=i;else{var s=d&&r.shorthandPropertyExpansions[a];if(s)for(var l in s)o[l]="";else o[a]=""}}}};a.measureMethods(C,"CSSPropertyOperations",{setValueForStyles:"setValueForStyles"}),e.exports=C}).call(t,n(5))},function(e,t){"use strict";function n(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}var r={animationIterationCount:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,stopOpacity:!0,strokeDashoffset:!0,strokeOpacity:!0,strokeWidth:!0},o=["Webkit","ms","Moz","O"];Object.keys(r).forEach(function(e){o.forEach(function(t){r[n(t,e)]=r[e]})});var 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}},i={isUnitlessNumber:r,shorthandPropertyExpansions:a};e.exports=i},function(e,t,n){"use strict";function r(e){return o(e.replace(a,"ms-"))}var o=n(100),a=/^-ms-/;e.exports=r},function(e,t){"use strict";function n(e){return e.replace(r,function(e,t){return t.toUpperCase()})}var r=/-(.)/g;e.exports=n},function(e,t,n){"use strict";function r(e,t){var n=null==t||"boolean"==typeof t||""===t;if(n)return"";var r=isNaN(t);return r||0===t||a.hasOwnProperty(e)&&a[e]?""+t:("string"==typeof t&&(t=t.trim()),t+"px")}var o=n(98),a=o.isUnitlessNumber;e.exports=r},function(e,t,n){"use strict";function r(e){return o(e).replace(a,"-ms-")}var o=n(103),a=/^ms-/;e.exports=r},function(e,t){"use strict";function n(e){return e.replace(r,"-$1").toLowerCase()}var r=/([A-Z])/g;e.exports=n},function(e,t){"use strict";function n(e){var t={};return function(n){return t.hasOwnProperty(n)||(t[n]=e.call(this,n)),t[n]}}e.exports=n},function(e,t){"use strict";var n={onClick:!0,onDoubleClick:!0,onMouseDown:!0,onMouseMove:!0,onMouseUp:!0,onClickCapture:!0,onDoubleClickCapture:!0,onMouseDownCapture:!0,onMouseMoveCapture:!0,onMouseUpCapture:!0},r={getNativeProps:function(e,t,r){if(!t.disabled)return t;var o={};for(var a in t)t.hasOwnProperty(a)&&!n[a]&&(o[a]=t[a]);return o}};e.exports=r},function(e,t,n){(function(t){"use strict";function r(){this._rootNodeID&&d.updateWrapper(this)}function o(e){var n=this._currentElement.props,o=i.executeOnChange(n,e);s.asap(r,this);var a=n.name;if("radio"===n.type&&null!=a){for(var l=u.getNode(this._rootNodeID),d=l;d.parentNode;)d=d.parentNode;for(var f=d.querySelectorAll("input[name="+JSON.stringify(""+a)+'][type="radio"]'),h=0;h<f.length;h++){var v=f[h];if(v!==l&&v.form===l.form){var m=u.getID(v);m?void 0:"production"!==t.env.NODE_ENV?c(!1,"ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported."):c(!1);var y=p[m];y?void 0:"production"!==t.env.NODE_ENV?c(!1,"ReactDOMInput: Unknown radio button ID %s.",m):c(!1),s.asap(r,y)}}}return o}var a=n(28),i=n(107),u=n(29),s=n(55),l=n(40),c=n(14),p={},d={getNativeProps:function(e,t,n){var r=i.getValue(t),o=i.getChecked(t),a=l({},t,{defaultChecked:void 0,defaultValue:void 0,value:null!=r?r:e._wrapperState.initialValue,checked:null!=o?o:e._wrapperState.initialChecked,onChange:e._wrapperState.onChange});return a},mountWrapper:function(e,n){"production"!==t.env.NODE_ENV&&i.checkPropTypes("input",n,e._currentElement._owner);var r=n.defaultValue;e._wrapperState={initialChecked:n.defaultChecked||!1,initialValue:null!=r?r:null,onChange:o.bind(e)}},mountReadyWrapper:function(e){p[e._rootNodeID]=e},unmountWrapper:function(e){delete p[e._rootNodeID]},updateWrapper:function(e){var t=e._currentElement.props,n=t.checked;null!=n&&a.updatePropertyByID(e._rootNodeID,"checked",n||!1);var r=i.getValue(t);null!=r&&a.updatePropertyByID(e._rootNodeID,"value",""+r)}};e.exports=d}).call(t,n(5))},function(e,t,n){(function(t){"use strict";function r(e){null!=e.checkedLink&&null!=e.valueLink?"production"!==t.env.NODE_ENV?l(!1,"Cannot provide a checkedLink and a valueLink. If you want to use checkedLink, you probably don't want to use valueLink and vice versa."):l(!1):void 0}function o(e){r(e),null!=e.value||null!=e.onChange?"production"!==t.env.NODE_ENV?l(!1,"Cannot provide a valueLink and a value or onChange event. If you want to use value or onChange, you probably don't want to use valueLink."):l(!1):void 0}function a(e){r(e),null!=e.checked||null!=e.onChange?"production"!==t.env.NODE_ENV?l(!1,"Cannot provide a checkedLink and a checked property or onChange event. If you want to use checked or onChange, you probably don't want to use checkedLink"):l(!1):void 0}function i(e){if(e){var t=e.getName();if(t)return" Check the render method of `"+t+"`."}return""}var u=n(108),s=n(66),l=n(14),c=n(26),p={button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0},d={value:function(e,t,n){return!e[t]||p[e.type]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.")},checked:function(e,t,n){return!e[t]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.")},onChange:u.func},f={},h={checkPropTypes:function(e,n,r){for(var o in d){if(d.hasOwnProperty(o))var a=d[o](n,o,e,s.prop);if(a instanceof Error&&!(a.message in f)){f[a.message]=!0;var u=i(r);"production"!==t.env.NODE_ENV?c(!1,"Failed form propType: %s%s",a.message,u):void 0}}},getValue:function(e){return e.valueLink?(o(e),e.valueLink.value):e.value},getChecked:function(e){return e.checkedLink?(a(e),e.checkedLink.value):e.checked},executeOnChange:function(e,t){return e.valueLink?(o(e),e.valueLink.requestChange(t.target.value)):e.checkedLink?(a(e),e.checkedLink.requestChange(t.target.checked)):e.onChange?e.onChange.call(void 0,t):void 0}};e.exports=h}).call(t,n(5))},function(e,t,n){"use strict";function r(e){function t(t,n,r,o,a,i){if(o=o||N,i=i||r,null==n[r]){var u=b[a];return t?new Error("Required "+u+" `"+i+"` was not specified in "+("`"+o+"`.")):null}return e(n,r,o,a,i)}var n=t.bind(null,!1);return n.isRequired=t.bind(null,!0),n}function o(e){function t(t,n,r,o,a){var i=t[n],u=v(i);if(u!==e){var s=b[o],l=m(i);return new Error("Invalid "+s+" `"+a+"` of type "+("`"+l+"` supplied to `"+r+"`, expected ")+("`"+e+"`."))}return null}return r(t)}function a(){return r(_.thatReturns(null))}function i(e){function t(t,n,r,o,a){var i=t[n];if(!Array.isArray(i)){var u=b[o],s=v(i);return new Error("Invalid "+u+" `"+a+"` of type "+("`"+s+"` supplied to `"+r+"`, expected an array."))}for(var l=0;l<i.length;l++){var c=e(i,l,r,o,a+"["+l+"]");if(c instanceof Error)return c}return null}return r(t)}function u(){function e(e,t,n,r,o){if(!g.isValidElement(e[t])){var a=b[r];return new Error("Invalid "+a+" `"+o+"` supplied to "+("`"+n+"`, expected a single ReactElement."))}return null}return r(e)}function s(e){function t(t,n,r,o,a){if(!(t[n]instanceof e)){var i=b[o],u=e.name||N,s=y(t[n]);return new Error("Invalid "+i+" `"+a+"` of type "+("`"+s+"` supplied to `"+r+"`, expected ")+("instance of `"+u+"`."))}return null}return r(t)}function l(e){function t(t,n,r,o,a){for(var i=t[n],u=0;u<e.length;u++)if(i===e[u])return null;var s=b[o],l=JSON.stringify(e);return new Error("Invalid "+s+" `"+a+"` of value `"+i+"` "+("supplied to `"+r+"`, expected one of "+l+"."))}return r(Array.isArray(e)?t:function(){return new Error("Invalid argument supplied to oneOf, expected an instance of array.")})}function c(e){function t(t,n,r,o,a){var i=t[n],u=v(i);if("object"!==u){var s=b[o];return new Error("Invalid "+s+" `"+a+"` of type "+("`"+u+"` supplied to `"+r+"`, expected an object."))}for(var l in i)if(i.hasOwnProperty(l)){var c=e(i,l,r,o,a+"."+l);if(c instanceof Error)return c}return null}return r(t)}function p(e){function t(t,n,r,o,a){for(var i=0;i<e.length;i++){var u=e[i];if(null==u(t,n,r,o,a))return null}var s=b[o];return new Error("Invalid "+s+" `"+a+"` supplied to "+("`"+r+"`."))}return r(Array.isArray(e)?t:function(){return new Error("Invalid argument supplied to oneOfType, expected an instance of array.")})}function d(){function e(e,t,n,r,o){if(!h(e[t])){var a=b[r];return new Error("Invalid "+a+" `"+o+"` supplied to "+("`"+n+"`, expected a ReactNode."))}return null}return r(e)}function f(e){function t(t,n,r,o,a){var i=t[n],u=v(i);if("object"!==u){var s=b[o];return new Error("Invalid "+s+" `"+a+"` of type `"+u+"` "+("supplied to `"+r+"`, expected `object`."))}for(var l in e){var c=e[l];if(c){var p=c(i,l,r,o,a+"."+l);if(p)return p}}return null}return r(t)}function h(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(h);if(null===e||g.isValidElement(e))return!0;var t=E(e);if(!t)return!1;var n,r=t.call(e);if(t!==e.entries){for(;!(n=r.next()).done;)if(!h(n.value))return!1}else for(;!(n=r.next()).done;){var o=n.value;if(o&&!h(o[1]))return!1}return!0;default:return!1}}function v(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":t}function m(e){var t=v(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}function y(e){return e.constructor&&e.constructor.name?e.constructor.name:"<<anonymous>>"}var g=n(43),b=n(67),_=n(16),E=n(109),N="<<anonymous>>",O={array:o("array"),bool:o("boolean"),func:o("function"),number:o("number"),object:o("object"),string:o("string"),any:a(),arrayOf:i,element:u(),instanceOf:s,node:d(),objectOf:c,oneOf:l,oneOfType:p,shape:f};e.exports=O},function(e,t){"use strict";function n(e){var t=e&&(r&&e[r]||e[o]);return"function"==typeof t?t:void 0}var r="function"==typeof Symbol&&Symbol.iterator,o="@@iterator";e.exports=n},function(e,t,n){(function(t){"use strict";var r=n(111),o=n(113),a=n(40),i=n(26),u=o.valueContextKey,s={mountWrapper:function(e,n,r){"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?i(null==n.selected,"Use the `defaultValue` or `value` props on <select> instead of setting `selected` on <option>."):void 0);var o=r[u],a=null;if(null!=o)if(a=!1,Array.isArray(o)){for(var s=0;s<o.length;s++)if(""+o[s]==""+n.value){a=!0;break}}else a=""+o==""+n.value;e._wrapperState={selected:a}},getNativeProps:function(e,n,o){var u=a({selected:void 0,children:void 0},n);null!=e._wrapperState.selected&&(u.selected=e._wrapperState.selected);var s="";return r.forEach(n.children,function(e){null!=e&&("string"==typeof e||"number"==typeof e?s+=e:"production"!==t.env.NODE_ENV?i(!1,"Only strings and numbers are supported as <option> children."):void 0)}),s&&(u.children=s),u}};e.exports=s}).call(t,n(5))},function(e,t,n){"use strict";function r(e){return(""+e).replace(_,"//")}function o(e,t){this.func=e,this.context=t,this.count=0}function a(e,t,n){var r=e.func,o=e.context;r.call(o,t,e.count++)}function i(e,t,n){if(null==e)return e;var r=o.getPooled(t,n);y(e,a,r),o.release(r)}function u(e,t,n,r){this.result=e,this.keyPrefix=t,this.func=n,this.context=r,this.count=0}function s(e,t,n){var o=e.result,a=e.keyPrefix,i=e.func,u=e.context,s=i.call(u,t,e.count++);Array.isArray(s)?l(s,o,n,m.thatReturnsArgument):null!=s&&(v.isValidElement(s)&&(s=v.cloneAndReplaceKey(s,a+(s!==t?r(s.key||"")+"/":"")+n)),o.push(s))}function l(e,t,n,o,a){var i="";null!=n&&(i=r(n)+"/");var l=u.getPooled(t,i,o,a);y(e,s,l),u.release(l)}function c(e,t,n){if(null==e)return e;var r=[];return l(e,r,null,t,n),r}function p(e,t,n){return null}function d(e,t){return y(e,p,null)}function f(e){var t=[];return l(e,t,null,m.thatReturnsArgument),t}var h=n(57),v=n(43),m=n(16),y=n(112),g=h.twoArgumentPooler,b=h.fourArgumentPooler,_=/\/(?!\/)/g;o.prototype.destructor=function(){this.func=null,this.context=null,this.count=0},h.addPoolingTo(o,g),u.prototype.destructor=function(){this.result=null,this.keyPrefix=null,this.func=null,this.context=null,this.count=0},h.addPoolingTo(u,b);var E={forEach:i,map:c,mapIntoWithKeyPrefixInternal:l,count:d,toArray:f};e.exports=E},function(e,t,n){(function(t){"use strict";function r(e){return y[e]}function o(e,t){return e&&null!=e.key?i(e.key):t.toString(36)}function a(e){return(""+e).replace(g,r)}function i(e){return"$"+a(e)}function u(e,n,r,a){var s=typeof e;if("undefined"!==s&&"boolean"!==s||(e=null),null===e||"string"===s||"number"===s||c.isValidElement(e))return r(a,e,""===n?v+o(e,0):n),1;var p,y,g=0,_=""===n?v:n+m;if(Array.isArray(e))for(var E=0;E<e.length;E++)p=e[E],y=_+o(p,E),g+=u(p,y,r,a);else{var N=d(e);if(N){var O,C=N.call(e);if(N!==e.entries)for(var P=0;!(O=C.next()).done;)p=O.value,y=_+o(p,P++),g+=u(p,y,r,a);else for("production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?h(b,"Using Maps as children is not yet fully supported. It is an experimental feature that might be removed. Convert it to a sequence / iterable of keyed ReactElements instead."):void 0,b=!0);!(O=C.next()).done;){var w=O.value;w&&(p=w[1],y=_+i(w[0])+m+o(p,0),g+=u(p,y,r,a))}}else if("object"===s){var T="";if("production"!==t.env.NODE_ENV&&(T=" If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons.",e._isReactElement&&(T=" It looks like you're using an element created by a different version of React. Make sure to use only one copy of React."),l.current)){var x=l.current.getName();x&&(T+=" Check the render method of `"+x+"`.")}var D=String(e);"production"!==t.env.NODE_ENV?f(!1,"Objects are not valid as a React child (found: %s).%s","[object Object]"===D?"object with keys {"+Object.keys(e).join(", ")+"}":D,T):f(!1)}}return g}function s(e,t,n){return null==e?0:u(e,"",t,n)}var l=n(6),c=n(43),p=n(46),d=n(109),f=n(14),h=n(26),v=p.SEPARATOR,m=":",y={"=":"=0",".":"=1",":":"=2"},g=/[=.:]/g,b=!1;e.exports=s}).call(t,n(5))},function(e,t,n){(function(t){"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 o(e){if(e){var t=e.getName();if(t)return" Check the render method of `"+t+"`."}return""}function a(e,n){var r=e._currentElement._owner;s.checkPropTypes("select",n,r);for(var a=0;a<h.length;a++){var i=h[a];null!=n[i]&&(n.multiple?"production"!==t.env.NODE_ENV?d(Array.isArray(n[i]),"The `%s` prop supplied to <select> must be an array if `multiple` is true.%s",i,o(r)):void 0:"production"!==t.env.NODE_ENV?d(!Array.isArray(n[i]),"The `%s` prop supplied to <select> must be a scalar value if `multiple` is false.%s",i,o(r)):void 0)}}function i(e,t,n){var r,o,a=l.getNode(e._rootNodeID).options;if(t){for(r={},o=0;o<n.length;o++)r[""+n[o]]=!0;for(o=0;o<a.length;o++){var i=r.hasOwnProperty(a[o].value);a[o].selected!==i&&(a[o].selected=i)}}else{for(r=""+n,o=0;o<a.length;o++)if(a[o].value===r)return void(a[o].selected=!0);a.length&&(a[0].selected=!0)}}function u(e){var t=this._currentElement.props,n=s.executeOnChange(t,e);return this._wrapperState.pendingUpdate=!0,c.asap(r,this),n}var s=n(107),l=n(29),c=n(55),p=n(40),d=n(26),f="__ReactDOMSelect_value$"+Math.random().toString(36).slice(2),h=["value","defaultValue"],v={valueContextKey:f,getNativeProps:function(e,t,n){return p({},t,{onChange:e._wrapperState.onChange,value:void 0})},mountWrapper:function(e,n){"production"!==t.env.NODE_ENV&&a(e,n);var r=s.getValue(n);e._wrapperState={pendingUpdate:!1,initialValue:null!=r?r:n.defaultValue,onChange:u.bind(e),wasMultiple:Boolean(n.multiple)}},processChildContext:function(e,t,n){var r=p({},n);return r[f]=e._wrapperState.initialValue,r},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?[]:""))}};e.exports=v}).call(t,n(5))},function(e,t,n){(function(t){"use strict";function r(){this._rootNodeID&&p.updateWrapper(this)}function o(e){var t=this._currentElement.props,n=a.executeOnChange(t,e);return u.asap(r,this),n}var a=n(107),i=n(28),u=n(55),s=n(40),l=n(14),c=n(26),p={getNativeProps:function(e,n,r){null!=n.dangerouslySetInnerHTML?"production"!==t.env.NODE_ENV?l(!1,"`dangerouslySetInnerHTML` does not make sense on <textarea>."):l(!1):void 0;var o=s({},n,{defaultValue:void 0,value:void 0,children:e._wrapperState.initialValue,onChange:e._wrapperState.onChange});return o},mountWrapper:function(e,n){"production"!==t.env.NODE_ENV&&a.checkPropTypes("textarea",n,e._currentElement._owner);var r=n.defaultValue,i=n.children;null!=i&&("production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?c(!1,"Use the `defaultValue` or `value` props instead of setting children on <textarea>."):void 0),null!=r?"production"!==t.env.NODE_ENV?l(!1,"If you supply `defaultValue` on a <textarea>, do not pass children."):l(!1):void 0,Array.isArray(i)&&(i.length<=1?void 0:"production"!==t.env.NODE_ENV?l(!1,"<textarea> can only have at most one child."):l(!1),i=i[0]),r=""+i),null==r&&(r="");var u=a.getValue(n);e._wrapperState={initialValue:""+(null!=u?u:r),onChange:o.bind(e)}},updateWrapper:function(e){var t=e._currentElement.props,n=a.getValue(t);null!=n&&i.updatePropertyByID(e._rootNodeID,"value",""+n)}};e.exports=p}).call(t,n(5))},function(e,t,n){(function(t){"use strict";function r(e,t,n){y.push({parentID:e,parentNode:null,type:p.INSERT_MARKUP,markupIndex:g.push(t)-1,content:null,fromIndex:null,toIndex:n})}function o(e,t,n){y.push({parentID:e,parentNode:null,type:p.MOVE_EXISTING,markupIndex:null,content:null,fromIndex:t,toIndex:n})}function a(e,t){y.push({parentID:e,parentNode:null,type:p.REMOVE_NODE,markupIndex:null,content:null,fromIndex:t,toIndex:null})}function i(e,t){y.push({parentID:e,parentNode:null,type:p.SET_MARKUP,markupIndex:null,content:t,fromIndex:null,toIndex:null})}function u(e,t){y.push({parentID:e,parentNode:null,type:p.TEXT_CONTENT,markupIndex:null,content:t,fromIndex:null,toIndex:null})}function s(){y.length&&(c.processChildrenUpdates(y,g),l())}function l(){y.length=0,g.length=0}var c=n(65),p=n(17),d=n(6),f=n(51),h=n(116),v=n(117),m=0,y=[],g=[],b={Mixin:{_reconcilerInstantiateChildren:function(e,n,r){if("production"!==t.env.NODE_ENV&&this._currentElement)try{return d.current=this._currentElement._owner,h.instantiateChildren(e,n,r)}finally{d.current=null}return h.instantiateChildren(e,n,r)},_reconcilerUpdateChildren:function(e,n,r,o){var a;if("production"!==t.env.NODE_ENV&&this._currentElement){try{d.current=this._currentElement._owner,a=v(n)}finally{d.current=null}return h.updateChildren(e,a,r,o)}return a=v(n),h.updateChildren(e,a,r,o)},mountChildren:function(e,t,n){var r=this._reconcilerInstantiateChildren(e,t,n);this._renderedChildren=r;var o=[],a=0;for(var i in r)if(r.hasOwnProperty(i)){var u=r[i],s=this._rootNodeID+i,l=f.mountComponent(u,s,t,n);u._mountIndex=a++,o.push(l)}return o},updateTextContent:function(e){m++;var t=!0;try{var n=this._renderedChildren;h.unmountChildren(n);for(var r in n)n.hasOwnProperty(r)&&this._unmountChild(n[r]);this.setTextContent(e),t=!1}finally{m--,m||(t?l():s())}},updateMarkup:function(e){m++;var t=!0;try{var n=this._renderedChildren;h.unmountChildren(n);for(var r in n)n.hasOwnProperty(r)&&this._unmountChildByName(n[r],r);this.setMarkup(e),t=!1}finally{m--,m||(t?l():s())}},updateChildren:function(e,t,n){m++;var r=!0;try{this._updateChildren(e,t,n),r=!1}finally{m--,m||(r?l():s())}},_updateChildren:function(e,t,n){var r=this._renderedChildren,o=this._reconcilerUpdateChildren(r,e,t,n);if(this._renderedChildren=o,o||r){var a,i=0,u=0;for(a in o)if(o.hasOwnProperty(a)){var s=r&&r[a],l=o[a];s===l?(this.moveChild(s,u,i),i=Math.max(s._mountIndex,i),s._mountIndex=u):(s&&(i=Math.max(s._mountIndex,i),this._unmountChild(s)),this._mountChildByNameAtIndex(l,a,u,t,n)),u++}for(a in r)!r.hasOwnProperty(a)||o&&o.hasOwnProperty(a)||this._unmountChild(r[a])}},unmountChildren:function(){var e=this._renderedChildren;h.unmountChildren(e),this._renderedChildren=null},moveChild:function(e,t,n){e._mountIndex<n&&o(this._rootNodeID,e._mountIndex,t)},createChild:function(e,t){r(this._rootNodeID,t,e._mountIndex)},removeChild:function(e){a(this._rootNodeID,e._mountIndex)},setTextContent:function(e){u(this._rootNodeID,e)},setMarkup:function(e){i(this._rootNodeID,e)},_mountChildByNameAtIndex:function(e,t,n,r,o){var a=this._rootNodeID+t,i=f.mountComponent(e,a,r,o);e._mountIndex=n,this.createChild(e,i)},_unmountChild:function(e){this.removeChild(e),e._mountIndex=null}}};e.exports=b}).call(t,n(5))},function(e,t,n){(function(t){"use strict";function r(e,n,r){var o=void 0===e[r];"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?s(o,"flattenChildren(...): Encountered two children with the same key, `%s`. Child keys must be unique; when two children share a key, only the first child will be used.",r):void 0),null!=n&&o&&(e[r]=a(n,null))}var o=n(51),a=n(63),i=n(68),u=n(112),s=n(26),l={instantiateChildren:function(e,t,n){if(null==e)return null;var o={};return u(e,r,o),o},updateChildren:function(e,t,n,r){if(!t&&!e)return null;var u;for(u in t)if(t.hasOwnProperty(u)){var s=e&&e[u],l=s&&s._currentElement,c=t[u];if(null!=s&&i(l,c))o.receiveComponent(s,c,n,r),t[u]=s;else{s&&o.unmountComponent(s,u);var p=a(c,null);t[u]=p}}for(u in e)!e.hasOwnProperty(u)||t&&t.hasOwnProperty(u)||o.unmountComponent(e[u]);return t},unmountChildren:function(e){for(var t in e)if(e.hasOwnProperty(t)){var n=e[t];o.unmountComponent(n)}}};e.exports=l}).call(t,n(5))},function(e,t,n){(function(t){"use strict";function r(e,n,r){var o=e,a=void 0===o[r];"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?i(a,"flattenChildren(...): Encountered two children with the same key, `%s`. Child keys must be unique; when two children share a key, only the first child will be used.",r):void 0),a&&null!=n&&(o[r]=n)}function o(e){if(null==e)return e;var t={};return a(e,r,t),t}var a=n(112),i=n(26);e.exports=o}).call(t,n(5))},function(e,t){"use strict";function n(e,t){if(e===t)return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var n=Object.keys(e),o=Object.keys(t);if(n.length!==o.length)return!1;for(var a=r.bind(t),i=0;i<n.length;i++)if(!a(n[i])||e[n[i]]!==t[n[i]])return!1; return!0}var r=Object.prototype.hasOwnProperty;e.exports=n},function(e,t,n){"use strict";function r(e){var t=d.getID(e),n=p.getReactRootIDFromNodeID(t),r=d.findReactContainerForID(n),o=d.getFirstReactDOM(r);return o}function o(e,t){this.topLevelType=e,this.nativeEvent=t,this.ancestors=[]}function a(e){i(e)}function i(e){for(var t=d.getFirstReactDOM(v(e.nativeEvent))||window,n=t;n;)e.ancestors.push(n),n=r(n);for(var o=0;o<e.ancestors.length;o++){t=e.ancestors[o];var a=d.getID(t)||"";y._handleTopLevel(e.topLevelType,t,a,e.nativeEvent,v(e.nativeEvent))}}function u(e){var t=m(window);e(t)}var s=n(120),l=n(10),c=n(57),p=n(46),d=n(29),f=n(55),h=n(40),v=n(82),m=n(121);h(o.prototype,{destructor:function(){this.topLevelType=null,this.nativeEvent=null,this.ancestors.length=0}}),c.addPoolingTo(o,c.twoArgumentPooler);var y={_enabled:!0,_handleTopLevel:null,WINDOW_HANDLE:l.canUseDOM?window:null,setHandleTopLevel:function(e){y._handleTopLevel=e},setEnabled:function(e){y._enabled=!!e},isEnabled:function(){return y._enabled},trapBubbledEvent:function(e,t,n){var r=n;return r?s.listen(r,t,y.dispatchEvent.bind(null,e)):null},trapCapturedEvent:function(e,t,n){var r=n;return r?s.capture(r,t,y.dispatchEvent.bind(null,e)):null},monitorScrollValue:function(e){var t=u.bind(null,e);s.listen(window,"scroll",t)},dispatchEvent:function(e,t){if(y._enabled){var n=o.getPooled(e,t);try{f.batchedUpdates(a,n)}finally{o.release(n)}}}};e.exports=y},function(e,t,n){(function(t){"use strict";var r=n(16),o={listen:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!1),{remove:function(){e.removeEventListener(t,n,!1)}}):e.attachEvent?(e.attachEvent("on"+t,n),{remove:function(){e.detachEvent("on"+t,n)}}):void 0},capture:function(e,n,o){return e.addEventListener?(e.addEventListener(n,o,!0),{remove:function(){e.removeEventListener(n,o,!0)}}):("production"!==t.env.NODE_ENV&&console.error("Attempted to listen to events during the capture phase on a browser that does not support the capture phase. Your application will not receive some events."),{remove:r})},registerDefault:function(){}};e.exports=o}).call(t,n(5))},function(e,t){"use strict";function n(e){return e===window?{x:window.pageXOffset||document.documentElement.scrollLeft,y:window.pageYOffset||document.documentElement.scrollTop}:{x:e.scrollLeft,y:e.scrollTop}}e.exports=n},function(e,t,n){"use strict";var r=n(24),o=n(32),a=n(65),i=n(123),u=n(69),s=n(30),l=n(70),c=n(19),p=n(47),d=n(55),f={Component:a.injection,Class:i.injection,DOMProperty:r.injection,EmptyComponent:u.injection,EventPluginHub:o.injection,EventEmitter:s.injection,NativeComponent:l.injection,Perf:c.injection,RootIndex:p.injection,Updates:d.injection};e.exports=f},function(e,t,n){(function(t){"use strict";function r(){T||(T=!0,"production"!==t.env.NODE_ENV?O(!1,"setProps(...) and replaceProps(...) are deprecated. Instead, call render again at the top level."):void 0)}function o(e,n,r){for(var o in n)n.hasOwnProperty(o)&&("production"!==t.env.NODE_ENV?O("function"==typeof n[o],"%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.",e.displayName||"ReactClass",m[r],o):void 0)}function a(e,n){var r=x.hasOwnProperty(n)?x[n]:null;M.hasOwnProperty(n)&&(r!==P.OVERRIDE_BASE?"production"!==t.env.NODE_ENV?_(!1,"ReactClassInterface: You are attempting to override `%s` from your class specification. Ensure that your method names do not overlap with React methods.",n):_(!1):void 0),e.hasOwnProperty(n)&&(r!==P.DEFINE_MANY&&r!==P.DEFINE_MANY_MERGED?"production"!==t.env.NODE_ENV?_(!1,"ReactClassInterface: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.",n):_(!1):void 0)}function i(e,n){if(n){"function"==typeof n?"production"!==t.env.NODE_ENV?_(!1,"ReactClass: You're attempting to use a component class as a mixin. Instead, just use a regular object."):_(!1):void 0,h.isValidElement(n)?"production"!==t.env.NODE_ENV?_(!1,"ReactClass: You're attempting to use a component as a mixin. Instead, just use a regular object."):_(!1):void 0;var r=e.prototype;n.hasOwnProperty(C)&&D.mixins(e,n.mixins);for(var o in n)if(n.hasOwnProperty(o)&&o!==C){var i=n[o];if(a(r,o),D.hasOwnProperty(o))D[o](e,i);else{var u=x.hasOwnProperty(o),s=r.hasOwnProperty(o),p="function"==typeof i,d=p&&!u&&!s&&n.autobind!==!1;if(d)r.__reactAutoBindMap||(r.__reactAutoBindMap={}),r.__reactAutoBindMap[o]=i,r[o]=i;else if(s){var f=x[o];!u||f!==P.DEFINE_MANY_MERGED&&f!==P.DEFINE_MANY?"production"!==t.env.NODE_ENV?_(!1,"ReactClass: Unexpected spec policy %s for key %s when mixing in component specs.",f,o):_(!1):void 0,f===P.DEFINE_MANY_MERGED?r[o]=l(r[o],i):f===P.DEFINE_MANY&&(r[o]=c(r[o],i))}else r[o]=i,"production"!==t.env.NODE_ENV&&"function"==typeof i&&n.displayName&&(r[o].displayName=n.displayName+"_"+o)}}}}function u(e,n){if(n)for(var r in n){var o=n[r];if(n.hasOwnProperty(r)){var a=r in D;a?"production"!==t.env.NODE_ENV?_(!1,'ReactClass: You are attempting to define a reserved property, `%s`, that shouldn\'t be on the "statics" key. Define it as an instance property instead; it will still be accessible on the constructor.',r):_(!1):void 0;var i=r in e;i?"production"!==t.env.NODE_ENV?_(!1,"ReactClass: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.",r):_(!1):void 0,e[r]=o}}}function s(e,n){e&&n&&"object"==typeof e&&"object"==typeof n?void 0:"production"!==t.env.NODE_ENV?_(!1,"mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects."):_(!1);for(var r in n)n.hasOwnProperty(r)&&(void 0!==e[r]?"production"!==t.env.NODE_ENV?_(!1,"mergeIntoWithNoDuplicateKeys(): Tried to merge two objects with the same key: `%s`. This conflict may be due to a mixin; in particular, this may be caused by two getInitialState() or getDefaultProps() methods returning objects with clashing keys.",r):_(!1):void 0,e[r]=n[r]);return e}function l(e,t){return function(){var n=e.apply(this,arguments),r=t.apply(this,arguments);if(null==n)return r;if(null==r)return n;var o={};return s(o,n),s(o,r),o}}function c(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}function p(e,n){var r=n.bind(e);if("production"!==t.env.NODE_ENV){r.__reactBoundContext=e,r.__reactBoundMethod=n,r.__reactBoundArguments=null;var o=e.constructor.displayName,a=r.bind;r.bind=function(i){for(var u=arguments.length,s=Array(u>1?u-1:0),l=1;u>l;l++)s[l-1]=arguments[l];if(i!==e&&null!==i)"production"!==t.env.NODE_ENV?O(!1,"bind(): React component methods may only be bound to the component instance. See %s",o):void 0;else if(!s.length)return"production"!==t.env.NODE_ENV?O(!1,"bind(): You are binding a component method to the component. React does this for you automatically in a high-performance way, so you can safely remove this call. See %s",o):void 0,r;var c=a.apply(r,arguments);return c.__reactBoundContext=e,c.__reactBoundMethod=n,c.__reactBoundArguments=s,c}}return r}function d(e){for(var t in e.__reactAutoBindMap)if(e.__reactAutoBindMap.hasOwnProperty(t)){var n=e.__reactAutoBindMap[t];e[t]=p(e,n)}}var f=n(124),h=n(43),v=n(66),m=n(67),y=n(125),g=n(40),b=n(59),_=n(14),E=n(18),N=n(80),O=n(26),C=N({mixins:null}),P=E({DEFINE_ONCE:null,DEFINE_MANY:null,OVERRIDE_BASE:null,DEFINE_MANY_MERGED:null}),w=[],T=!1,x={mixins:P.DEFINE_MANY,statics:P.DEFINE_MANY,propTypes:P.DEFINE_MANY,contextTypes:P.DEFINE_MANY,childContextTypes:P.DEFINE_MANY,getDefaultProps:P.DEFINE_MANY_MERGED,getInitialState:P.DEFINE_MANY_MERGED,getChildContext:P.DEFINE_MANY_MERGED,render:P.DEFINE_ONCE,componentWillMount:P.DEFINE_MANY,componentDidMount:P.DEFINE_MANY,componentWillReceiveProps:P.DEFINE_MANY,shouldComponentUpdate:P.DEFINE_ONCE,componentWillUpdate:P.DEFINE_MANY,componentDidUpdate:P.DEFINE_MANY,componentWillUnmount:P.DEFINE_MANY,updateComponent:P.OVERRIDE_BASE},D={displayName:function(e,t){e.displayName=t},mixins:function(e,t){if(t)for(var n=0;n<t.length;n++)i(e,t[n])},childContextTypes:function(e,n){"production"!==t.env.NODE_ENV&&o(e,n,v.childContext),e.childContextTypes=g({},e.childContextTypes,n)},contextTypes:function(e,n){"production"!==t.env.NODE_ENV&&o(e,n,v.context),e.contextTypes=g({},e.contextTypes,n)},getDefaultProps:function(e,t){e.getDefaultProps?e.getDefaultProps=l(e.getDefaultProps,t):e.getDefaultProps=t},propTypes:function(e,n){"production"!==t.env.NODE_ENV&&o(e,n,v.prop),e.propTypes=g({},e.propTypes,n)},statics:function(e,t){u(e,t)},autobind:function(){}},M={replaceState:function(e,t){this.updater.enqueueReplaceState(this,e),t&&this.updater.enqueueCallback(this,t)},isMounted:function(){return this.updater.isMounted(this)},setProps:function(e,n){"production"!==t.env.NODE_ENV&&r(),this.updater.enqueueSetProps(this,e),n&&this.updater.enqueueCallback(this,n)},replaceProps:function(e,n){"production"!==t.env.NODE_ENV&&r(),this.updater.enqueueReplaceProps(this,e),n&&this.updater.enqueueCallback(this,n)}},k=function(){};g(k.prototype,f.prototype,M);var S={createClass:function(e){var n=function(e,r,o){"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?O(this instanceof n,"Something is calling a React component directly. Use a factory or JSX instead. See: https://fb.me/react-legacyfactory"):void 0),this.__reactAutoBindMap&&d(this),this.props=e,this.context=r,this.refs=b,this.updater=o||y,this.state=null;var a=this.getInitialState?this.getInitialState():null;"production"!==t.env.NODE_ENV&&"undefined"==typeof a&&this.getInitialState._isMockFunction&&(a=null),"object"!=typeof a||Array.isArray(a)?"production"!==t.env.NODE_ENV?_(!1,"%s.getInitialState(): must return an object or null",n.displayName||"ReactCompositeComponent"):_(!1):void 0,this.state=a};n.prototype=new k,n.prototype.constructor=n,w.forEach(i.bind(null,n)),i(n,e),n.getDefaultProps&&(n.defaultProps=n.getDefaultProps()),"production"!==t.env.NODE_ENV&&(n.getDefaultProps&&(n.getDefaultProps.isReactClassApproved={}),n.prototype.getInitialState&&(n.prototype.getInitialState.isReactClassApproved={})),n.prototype.render?void 0:"production"!==t.env.NODE_ENV?_(!1,"createClass(...): Class specification must implement a `render` method."):_(!1),"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?O(!n.prototype.componentShouldUpdate,"%s has a method called componentShouldUpdate(). Did you mean shouldComponentUpdate()? The name is phrased as a question because the function is expected to return a value.",e.displayName||"A component"):void 0,"production"!==t.env.NODE_ENV?O(!n.prototype.componentWillRecieveProps,"%s has a method called componentWillRecieveProps(). Did you mean componentWillReceiveProps()?",e.displayName||"A component"):void 0);for(var r in x)n.prototype[r]||(n.prototype[r]=null);return n},injection:{injectMixin:function(e){w.push(e)}}};e.exports=S}).call(t,n(5))},function(e,t,n){(function(t){"use strict";function r(e,t,n){this.props=e,this.context=t,this.refs=i,this.updater=n||o}var o=n(125),a=n(44),i=n(59),u=n(14),s=n(26);if(r.prototype.isReactComponent={},r.prototype.setState=function(e,n){"object"!=typeof e&&"function"!=typeof e&&null!=e?"production"!==t.env.NODE_ENV?u(!1,"setState(...): takes an object of state variables to update or a function which returns an object of state variables."):u(!1):void 0,"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?s(null!=e,"setState(...): You passed an undefined or null state object; instead, use forceUpdate()."):void 0),this.updater.enqueueSetState(this,e),n&&this.updater.enqueueCallback(this,n)},r.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this),e&&this.updater.enqueueCallback(this,e)},"production"!==t.env.NODE_ENV){var l={getDOMNode:["getDOMNode","Use ReactDOM.findDOMNode(component) instead."],isMounted:["isMounted","Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."],replaceProps:["replaceProps","Instead, call render again at the top level."],replaceState:["replaceState","Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."],setProps:["setProps","Instead, call render again at the top level."]},c=function(e,n){a&&Object.defineProperty(r.prototype,e,{get:function(){"production"!==t.env.NODE_ENV?s(!1,"%s(...) is deprecated in plain JavaScript React classes. %s",n[0],n[1]):void 0}})};for(var p in l)l.hasOwnProperty(p)&&c(p,l[p])}e.exports=r}).call(t,n(5))},function(e,t,n){(function(t){"use strict";function r(e,n){"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?o(!1,"%s(...): Can only update a mounted or mounting component. This usually means you called %s() on an unmounted component. This is a no-op. Please check the code for the %s component.",n,n,e.constructor&&e.constructor.displayName||""):void 0)}var o=n(26),a={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")},enqueueSetProps:function(e,t){r(e,"setProps")},enqueueReplaceProps:function(e,t){r(e,"replaceProps")}};e.exports=a}).call(t,n(5))},function(e,t,n){"use strict";function r(e){this.reinitializeTransaction(),this.renderToStaticMarkup=!1,this.reactMountReady=o.getPooled(null),this.useCreateElement=!e&&u.useCreateElement}var o=n(56),a=n(57),i=n(30),u=n(42),s=n(127),l=n(58),c=n(40),p={initialize:s.getSelectionInformation,close:s.restoreSelection},d={initialize:function(){var e=i.isEnabled();return i.setEnabled(!1),e},close:function(e){i.setEnabled(e)}},f={initialize:function(){this.reactMountReady.reset()},close:function(){this.reactMountReady.notifyAll()}},h=[p,d,f],v={getTransactionWrappers:function(){return h},getReactMountReady:function(){return this.reactMountReady},destructor:function(){o.release(this.reactMountReady),this.reactMountReady=null}};c(r.prototype,l.Mixin,v),a.addPoolingTo(r),e.exports=r},function(e,t,n){"use strict";function r(e){return a(document.documentElement,e)}var o=n(128),a=n(60),i=n(96),u=n(130),s={hasSelectionCapabilities:function(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&"text"===e.type||"textarea"===t||"true"===e.contentEditable)},getSelectionInformation:function(){var e=u();return{focusedElem:e,selectionRange:s.hasSelectionCapabilities(e)?s.getSelection(e):null}},restoreSelection:function(e){var t=u(),n=e.focusedElem,o=e.selectionRange;t!==n&&r(n)&&(s.hasSelectionCapabilities(n)&&s.setSelection(n,o),i(n))},getSelection:function(e){var t;if("selectionStart"in e)t={start:e.selectionStart,end:e.selectionEnd};else if(document.selection&&e.nodeName&&"input"===e.nodeName.toLowerCase()){var n=document.selection.createRange();n.parentElement()===e&&(t={start:-n.moveStart("character",-e.value.length),end:-n.moveEnd("character",-e.value.length)})}else t=o.getOffsets(e);return t||{start:0,end:0}},setSelection:function(e,t){var n=t.start,r=t.end;if("undefined"==typeof 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 a=e.createTextRange();a.collapse(!0),a.moveStart("character",n),a.moveEnd("character",r-n),a.select()}else o.setOffsets(e,t)}};e.exports=s},function(e,t,n){"use strict";function r(e,t,n,r){return e===n&&t===r}function o(e){var t=document.selection,n=t.createRange(),r=n.text.length,o=n.duplicate();o.moveToElementText(e),o.setEndPoint("EndToStart",n);var a=o.text.length,i=a+r;return{start:a,end:i}}function a(e){var t=window.getSelection&&window.getSelection();if(!t||0===t.rangeCount)return null;var n=t.anchorNode,o=t.anchorOffset,a=t.focusNode,i=t.focusOffset,u=t.getRangeAt(0);try{u.startContainer.nodeType,u.endContainer.nodeType}catch(s){return null}var l=r(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset),c=l?0:u.toString().length,p=u.cloneRange();p.selectNodeContents(e),p.setEnd(u.startContainer,u.startOffset);var d=r(p.startContainer,p.startOffset,p.endContainer,p.endOffset),f=d?0:p.toString().length,h=f+c,v=document.createRange();v.setStart(n,o),v.setEnd(a,i);var m=v.collapsed;return{start:m?h:f,end:m?f:h}}function i(e,t){var n,r,o=document.selection.createRange().duplicate();"undefined"==typeof t.end?(n=t.start,r=n):t.start>t.end?(n=t.end,r=t.start):(n=t.start,r=t.end),o.moveToElementText(e),o.moveStart("character",n),o.setEndPoint("EndToStart",o),o.moveEnd("character",r-n),o.select()}function u(e,t){if(window.getSelection){var n=window.getSelection(),r=e[c()].length,o=Math.min(t.start,r),a="undefined"==typeof t.end?o:Math.min(t.end,r);if(!n.extend&&o>a){var i=a;a=o,o=i}var u=l(e,o),s=l(e,a);if(u&&s){var p=document.createRange();p.setStart(u.node,u.offset),n.removeAllRanges(),o>a?(n.addRange(p),n.extend(s.node,s.offset)):(p.setEnd(s.node,s.offset),n.addRange(p))}}}var s=n(10),l=n(129),c=n(76),p=s.canUseDOM&&"selection"in document&&!("getSelection"in window),d={getOffsets:p?o:a,setOffsets:p?i:u};e.exports=d},function(e,t){"use strict";function n(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function r(e){for(;e;){if(e.nextSibling)return e.nextSibling;e=e.parentNode}}function o(e,t){for(var o=n(e),a=0,i=0;o;){if(3===o.nodeType){if(i=a+o.textContent.length,t>=a&&i>=t)return{node:o,offset:t-a};a=i}o=n(r(o))}}e.exports=o},function(e,t){"use strict";function n(){if("undefined"==typeof document)return null;try{return document.activeElement||document.body}catch(e){return document.body}}e.exports=n},function(e,t,n){"use strict";function r(e){if("selectionStart"in e&&s.hasSelectionCapabilities(e))return{start:e.selectionStart,end:e.selectionEnd};if(window.getSelection){var t=window.getSelection();return{anchorNode:t.anchorNode,anchorOffset:t.anchorOffset,focusNode:t.focusNode,focusOffset:t.focusOffset}}if(document.selection){var n=document.selection.createRange();return{parentElement:n.parentElement(),text:n.text,top:n.boundingTop,left:n.boundingLeft}}}function o(e,t){if(_||null==y||y!==c())return null;var n=r(y);if(!b||!f(b,n)){b=n;var o=l.getPooled(m.select,g,e,t);return o.type="select",o.target=y,i.accumulateTwoPhaseDispatches(o),o}return null}var a=n(31),i=n(74),u=n(10),s=n(127),l=n(78),c=n(130),p=n(83),d=n(80),f=n(118),h=a.topLevelTypes,v=u.canUseDOM&&"documentMode"in document&&document.documentMode<=11,m={select:{phasedRegistrationNames:{bubbled:d({onSelect:null}),captured:d({onSelectCapture:null})},dependencies:[h.topBlur,h.topContextMenu,h.topFocus,h.topKeyDown,h.topMouseDown,h.topMouseUp,h.topSelectionChange]}},y=null,g=null,b=null,_=!1,E=!1,N=d({onSelect:null}),O={eventTypes:m,extractEvents:function(e,t,n,r,a){if(!E)return null;switch(e){case h.topFocus:(p(t)||"true"===t.contentEditable)&&(y=t,g=n,b=null);break;case h.topBlur:y=null,g=null,b=null;break;case h.topMouseDown:_=!0;break;case h.topContextMenu:case h.topMouseUp:return _=!1,o(r,a);case h.topSelectionChange:if(v)break;case h.topKeyDown:case h.topKeyUp:return o(r,a)}return null},didPutListener:function(e,t,n){t===N&&(E=!0)}};e.exports=O},function(e,t){"use strict";var n=Math.pow(2,53),r={createReactRootIndex:function(){return Math.ceil(Math.random()*n)}};e.exports=r},function(e,t,n){(function(t){"use strict";var r=n(31),o=n(120),a=n(74),i=n(29),u=n(134),s=n(78),l=n(135),c=n(136),p=n(87),d=n(139),f=n(140),h=n(88),v=n(141),m=n(16),y=n(137),g=n(14),b=n(80),_=r.topLevelTypes,E={abort:{phasedRegistrationNames:{bubbled:b({onAbort:!0}),captured:b({onAbortCapture:!0})}},blur:{phasedRegistrationNames:{bubbled:b({onBlur:!0}),captured:b({onBlurCapture:!0})}},canPlay:{phasedRegistrationNames:{bubbled:b({onCanPlay:!0}),captured:b({onCanPlayCapture:!0})}},canPlayThrough:{phasedRegistrationNames:{bubbled:b({onCanPlayThrough:!0}),captured:b({onCanPlayThroughCapture:!0})}},click:{phasedRegistrationNames:{bubbled:b({onClick:!0}),captured:b({onClickCapture:!0})}},contextMenu:{phasedRegistrationNames:{bubbled:b({onContextMenu:!0}),captured:b({onContextMenuCapture:!0})}},copy:{phasedRegistrationNames:{bubbled:b({onCopy:!0}),captured:b({onCopyCapture:!0})}},cut:{phasedRegistrationNames:{bubbled:b({onCut:!0}),captured:b({onCutCapture:!0})}},doubleClick:{phasedRegistrationNames:{bubbled:b({onDoubleClick:!0}),captured:b({onDoubleClickCapture:!0})}},drag:{phasedRegistrationNames:{bubbled:b({onDrag:!0}),captured:b({onDragCapture:!0})}},dragEnd:{phasedRegistrationNames:{bubbled:b({onDragEnd:!0}),captured:b({onDragEndCapture:!0})}},dragEnter:{phasedRegistrationNames:{bubbled:b({onDragEnter:!0}),captured:b({onDragEnterCapture:!0})}},dragExit:{phasedRegistrationNames:{bubbled:b({onDragExit:!0}),captured:b({onDragExitCapture:!0})}},dragLeave:{phasedRegistrationNames:{bubbled:b({onDragLeave:!0}),captured:b({onDragLeaveCapture:!0})}},dragOver:{phasedRegistrationNames:{bubbled:b({onDragOver:!0}),captured:b({onDragOverCapture:!0})}},dragStart:{phasedRegistrationNames:{bubbled:b({onDragStart:!0}),captured:b({onDragStartCapture:!0})}},drop:{phasedRegistrationNames:{bubbled:b({onDrop:!0}),captured:b({onDropCapture:!0})}},durationChange:{phasedRegistrationNames:{bubbled:b({onDurationChange:!0}),captured:b({onDurationChangeCapture:!0})}},emptied:{phasedRegistrationNames:{bubbled:b({onEmptied:!0}),captured:b({onEmptiedCapture:!0})}},encrypted:{phasedRegistrationNames:{bubbled:b({onEncrypted:!0}),captured:b({onEncryptedCapture:!0})}},ended:{phasedRegistrationNames:{bubbled:b({onEnded:!0}),captured:b({onEndedCapture:!0})}},error:{phasedRegistrationNames:{bubbled:b({onError:!0}),captured:b({onErrorCapture:!0})}},focus:{phasedRegistrationNames:{bubbled:b({onFocus:!0}),captured:b({onFocusCapture:!0})}},input:{phasedRegistrationNames:{bubbled:b({onInput:!0}),captured:b({onInputCapture:!0})}},keyDown:{phasedRegistrationNames:{bubbled:b({onKeyDown:!0}),captured:b({onKeyDownCapture:!0})}},keyPress:{phasedRegistrationNames:{bubbled:b({onKeyPress:!0}),captured:b({onKeyPressCapture:!0})}},keyUp:{phasedRegistrationNames:{bubbled:b({onKeyUp:!0}),captured:b({onKeyUpCapture:!0})}},load:{phasedRegistrationNames:{bubbled:b({onLoad:!0}),captured:b({onLoadCapture:!0})}},loadedData:{phasedRegistrationNames:{bubbled:b({onLoadedData:!0}),captured:b({onLoadedDataCapture:!0})}},loadedMetadata:{phasedRegistrationNames:{bubbled:b({onLoadedMetadata:!0}),captured:b({onLoadedMetadataCapture:!0})}},loadStart:{phasedRegistrationNames:{bubbled:b({onLoadStart:!0}),captured:b({onLoadStartCapture:!0})}},mouseDown:{phasedRegistrationNames:{bubbled:b({onMouseDown:!0}),captured:b({onMouseDownCapture:!0})}},mouseMove:{phasedRegistrationNames:{bubbled:b({onMouseMove:!0}),captured:b({onMouseMoveCapture:!0})}},mouseOut:{phasedRegistrationNames:{bubbled:b({onMouseOut:!0}),captured:b({onMouseOutCapture:!0})}},mouseOver:{phasedRegistrationNames:{bubbled:b({onMouseOver:!0}),captured:b({onMouseOverCapture:!0})}},mouseUp:{phasedRegistrationNames:{bubbled:b({onMouseUp:!0}),captured:b({onMouseUpCapture:!0})}},paste:{phasedRegistrationNames:{bubbled:b({onPaste:!0}),captured:b({onPasteCapture:!0})}},pause:{phasedRegistrationNames:{bubbled:b({onPause:!0}),captured:b({onPauseCapture:!0})}},play:{phasedRegistrationNames:{bubbled:b({onPlay:!0}),captured:b({onPlayCapture:!0})}},playing:{phasedRegistrationNames:{bubbled:b({onPlaying:!0}),captured:b({onPlayingCapture:!0})}},progress:{phasedRegistrationNames:{bubbled:b({onProgress:!0}),captured:b({onProgressCapture:!0})}},rateChange:{phasedRegistrationNames:{bubbled:b({onRateChange:!0}),captured:b({onRateChangeCapture:!0})}},reset:{phasedRegistrationNames:{bubbled:b({onReset:!0}),captured:b({onResetCapture:!0})}},scroll:{phasedRegistrationNames:{bubbled:b({onScroll:!0}),captured:b({onScrollCapture:!0})}},seeked:{phasedRegistrationNames:{bubbled:b({onSeeked:!0}),captured:b({onSeekedCapture:!0})}},seeking:{phasedRegistrationNames:{bubbled:b({onSeeking:!0}),captured:b({onSeekingCapture:!0})}},stalled:{phasedRegistrationNames:{bubbled:b({onStalled:!0}),captured:b({onStalledCapture:!0})}},submit:{phasedRegistrationNames:{bubbled:b({onSubmit:!0}),captured:b({onSubmitCapture:!0})}},suspend:{phasedRegistrationNames:{bubbled:b({onSuspend:!0}),captured:b({onSuspendCapture:!0})}},timeUpdate:{phasedRegistrationNames:{bubbled:b({onTimeUpdate:!0}),captured:b({onTimeUpdateCapture:!0})}},touchCancel:{phasedRegistrationNames:{bubbled:b({onTouchCancel:!0}),captured:b({onTouchCancelCapture:!0})}},touchEnd:{phasedRegistrationNames:{bubbled:b({onTouchEnd:!0}),captured:b({onTouchEndCapture:!0})}},touchMove:{phasedRegistrationNames:{bubbled:b({onTouchMove:!0}),captured:b({onTouchMoveCapture:!0})}},touchStart:{phasedRegistrationNames:{bubbled:b({onTouchStart:!0}),captured:b({onTouchStartCapture:!0})}},volumeChange:{phasedRegistrationNames:{bubbled:b({onVolumeChange:!0}),captured:b({onVolumeChangeCapture:!0})}},waiting:{phasedRegistrationNames:{bubbled:b({onWaiting:!0}),captured:b({onWaitingCapture:!0})}},wheel:{phasedRegistrationNames:{bubbled:b({onWheel:!0}),captured:b({onWheelCapture:!0})}}},N={topAbort:E.abort,topBlur:E.blur,topCanPlay:E.canPlay,topCanPlayThrough:E.canPlayThrough,topClick:E.click,topContextMenu:E.contextMenu,topCopy:E.copy,topCut:E.cut,topDoubleClick:E.doubleClick,topDrag:E.drag,topDragEnd:E.dragEnd,topDragEnter:E.dragEnter,topDragExit:E.dragExit,topDragLeave:E.dragLeave,topDragOver:E.dragOver,topDragStart:E.dragStart,topDrop:E.drop,topDurationChange:E.durationChange,topEmptied:E.emptied,topEncrypted:E.encrypted,topEnded:E.ended,topError:E.error,topFocus:E.focus,topInput:E.input,topKeyDown:E.keyDown,topKeyPress:E.keyPress,topKeyUp:E.keyUp,topLoad:E.load,topLoadedData:E.loadedData,topLoadedMetadata:E.loadedMetadata,topLoadStart:E.loadStart,topMouseDown:E.mouseDown,topMouseMove:E.mouseMove,topMouseOut:E.mouseOut,topMouseOver:E.mouseOver,topMouseUp:E.mouseUp,topPaste:E.paste,topPause:E.pause,topPlay:E.play,topPlaying:E.playing,topProgress:E.progress,topRateChange:E.rateChange,topReset:E.reset,topScroll:E.scroll,topSeeked:E.seeked,topSeeking:E.seeking,topStalled:E.stalled,topSubmit:E.submit,topSuspend:E.suspend,topTimeUpdate:E.timeUpdate,topTouchCancel:E.touchCancel,topTouchEnd:E.touchEnd,topTouchMove:E.touchMove,topTouchStart:E.touchStart,topVolumeChange:E.volumeChange,topWaiting:E.waiting,topWheel:E.wheel};for(var O in N)N[O].dependencies=[O];var C=b({onClick:null}),P={},w={eventTypes:E,extractEvents:function(e,n,r,o,i){var m=N[e];if(!m)return null;var b;switch(e){case _.topAbort:case _.topCanPlay:case _.topCanPlayThrough:case _.topDurationChange:case _.topEmptied:case _.topEncrypted:case _.topEnded:case _.topError:case _.topInput: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:b=s;break;case _.topKeyPress:if(0===y(o))return null;case _.topKeyDown:case _.topKeyUp:b=c;break;case _.topBlur:case _.topFocus:b=l;break;case _.topClick:if(2===o.button)return null;case _.topContextMenu:case _.topDoubleClick:case _.topMouseDown:case _.topMouseMove:case _.topMouseOut:case _.topMouseOver:case _.topMouseUp:b=p;break;case _.topDrag:case _.topDragEnd:case _.topDragEnter:case _.topDragExit:case _.topDragLeave:case _.topDragOver:case _.topDragStart:case _.topDrop:b=d;break;case _.topTouchCancel:case _.topTouchEnd:case _.topTouchMove:case _.topTouchStart:b=f;break;case _.topScroll:b=h;break;case _.topWheel:b=v;break;case _.topCopy:case _.topCut:case _.topPaste:b=u}b?void 0:"production"!==t.env.NODE_ENV?g(!1,"SimpleEventPlugin: Unhandled event type, `%s`.",e):g(!1);var E=b.getPooled(m,r,o,i);return a.accumulateTwoPhaseDispatches(E),E},didPutListener:function(e,t,n){if(t===C){var r=i.getNode(e);P[e]||(P[e]=o.listen(r,"click",m))}},willDeleteListener:function(e,t){t===C&&(P[e].remove(),delete P[e])}};e.exports=w}).call(t,n(5))},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(78),a={clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}};o.augmentClass(r,a),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(88),a={relatedTarget:null};o.augmentClass(r,a),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(88),a=n(137),i=n(138),u=n(89),s={key:i,location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:u,charCode:function(e){return"keypress"===e.type?a(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?a(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}};o.augmentClass(r,s),e.exports=r},function(e,t){"use strict";function n(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}e.exports=n},function(e,t,n){"use strict";function r(e){if(e.key){var t=a[e.key]||e.key;if("Unidentified"!==t)return t}if("keypress"===e.type){var n=o(e);return 13===n?"Enter":String.fromCharCode(n)}return"keydown"===e.type||"keyup"===e.type?i[e.keyCode]||"Unidentified":""}var o=n(137),a={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},i={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"};e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(87),a={dataTransfer:null};o.augmentClass(r,a),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(88),a=n(89),i={touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:a};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){o.call(this,e,t,n,r)}var o=n(87),a={deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:null,deltaMode:null};o.augmentClass(r,a),e.exports=r},function(e,t,n){"use strict";var r=n(24),o=r.injection.MUST_USE_ATTRIBUTE,a={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"},i={Properties:{clipPath:o,cx:o,cy:o,d:o,dx:o,dy:o,fill:o,fillOpacity:o,fontFamily:o,fontSize:o,fx:o,fy:o,gradientTransform:o,gradientUnits:o,markerEnd:o,markerMid:o,markerStart:o,offset:o,opacity:o,patternContentUnits:o,patternUnits:o,points:o,preserveAspectRatio:o,r:o,rx:o,ry:o,spreadMethod:o,stopColor:o,stopOpacity:o,stroke:o,strokeDasharray:o,strokeLinecap:o,strokeOpacity:o,strokeWidth:o,textAnchor:o,transform:o,version:o,viewBox:o,x1:o,x2:o,x:o,xlinkActuate:o,xlinkArcrole:o,xlinkHref:o,xlinkRole:o,xlinkShow:o,xlinkTitle:o,xlinkType:o,xmlBase:o,xmlLang:o,xmlSpace:o,y1:o,y2:o,y:o},DOMAttributeNamespaces:{xlinkActuate:a.xlink,xlinkArcrole:a.xlink,xlinkHref:a.xlink,xlinkRole:a.xlink,xlinkShow:a.xlink,xlinkTitle:a.xlink,xlinkType:a.xlink,xmlBase:a.xml,xmlLang:a.xml,xmlSpace:a.xml},DOMAttributeNames:{clipPath:"clip-path",fillOpacity:"fill-opacity",fontFamily:"font-family",fontSize:"font-size",gradientTransform:"gradientTransform",gradientUnits:"gradientUnits",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",patternContentUnits:"patternContentUnits",patternUnits:"patternUnits",preserveAspectRatio:"preserveAspectRatio",spreadMethod:"spreadMethod",stopColor:"stop-color",stopOpacity:"stop-opacity",strokeDasharray:"stroke-dasharray",strokeLinecap:"stroke-linecap",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",textAnchor:"text-anchor",viewBox:"viewBox",xlinkActuate:"xlink:actuate", xlinkArcrole:"xlink:arcrole",xlinkHref:"xlink:href",xlinkRole:"xlink:role",xlinkShow:"xlink:show",xlinkTitle:"xlink:title",xlinkType:"xlink:type",xmlBase:"xml:base",xmlLang:"xml:lang",xmlSpace:"xml:space"}};e.exports=i},function(e,t,n){"use strict";function r(e){return Math.floor(100*e)/100}function o(e,t,n){e[t]=(e[t]||0)+n}var a=n(24),i=n(144),u=n(29),s=n(19),l=n(145),c={_allMeasurements:[],_mountStack:[0],_injected:!1,start:function(){c._injected||s.injection.injectMeasure(c.measure),c._allMeasurements.length=0,s.enableMeasure=!0},stop:function(){s.enableMeasure=!1},getLastMeasurements:function(){return c._allMeasurements},printExclusive:function(e){e=e||c._allMeasurements;var t=i.getExclusiveSummary(e);console.table(t.map(function(e){return{"Component class name":e.componentName,"Total inclusive time (ms)":r(e.inclusive),"Exclusive mount time (ms)":r(e.exclusive),"Exclusive render time (ms)":r(e.render),"Mount time per instance (ms)":r(e.exclusive/e.count),"Render time per instance (ms)":r(e.render/e.count),Instances:e.count}}))},printInclusive:function(e){e=e||c._allMeasurements;var t=i.getInclusiveSummary(e);console.table(t.map(function(e){return{"Owner > component":e.componentName,"Inclusive time (ms)":r(e.time),Instances:e.count}})),console.log("Total time:",i.getTotalTime(e).toFixed(2)+" ms")},getMeasurementsSummaryMap:function(e){var t=i.getInclusiveSummary(e,!0);return t.map(function(e){return{"Owner > component":e.componentName,"Wasted time (ms)":e.time,Instances:e.count}})},printWasted:function(e){e=e||c._allMeasurements,console.table(c.getMeasurementsSummaryMap(e)),console.log("Total time:",i.getTotalTime(e).toFixed(2)+" ms")},printDOM:function(e){e=e||c._allMeasurements;var t=i.getDOMSummary(e);console.table(t.map(function(e){var t={};return t[a.ID_ATTRIBUTE_NAME]=e.id,t.type=e.type,t.args=JSON.stringify(e.args),t})),console.log("Total time:",i.getTotalTime(e).toFixed(2)+" ms")},_recordWrite:function(e,t,n,r){var o=c._allMeasurements[c._allMeasurements.length-1].writes;o[e]=o[e]||[],o[e].push({type:t,time:n,args:r})},measure:function(e,t,n){return function(){for(var r=arguments.length,a=Array(r),i=0;r>i;i++)a[i]=arguments[i];var s,p,d;if("_renderNewRootComponent"===t||"flushBatchedUpdates"===t)return c._allMeasurements.push({exclusive:{},inclusive:{},render:{},counts:{},writes:{},displayNames:{},totalTime:0,created:{}}),d=l(),p=n.apply(this,a),c._allMeasurements[c._allMeasurements.length-1].totalTime=l()-d,p;if("_mountImageIntoNode"===t||"ReactBrowserEventEmitter"===e||"ReactDOMIDOperations"===e||"CSSPropertyOperations"===e||"DOMChildrenOperations"===e||"DOMPropertyOperations"===e){if(d=l(),p=n.apply(this,a),s=l()-d,"_mountImageIntoNode"===t){var f=u.getID(a[1]);c._recordWrite(f,t,s,a[0])}else if("dangerouslyProcessChildrenUpdates"===t)a[0].forEach(function(e){var t={};null!==e.fromIndex&&(t.fromIndex=e.fromIndex),null!==e.toIndex&&(t.toIndex=e.toIndex),null!==e.textContent&&(t.textContent=e.textContent),null!==e.markupIndex&&(t.markup=a[1][e.markupIndex]),c._recordWrite(e.parentID,e.type,s,t)});else{var h=a[0];"object"==typeof h&&(h=u.getID(a[0])),c._recordWrite(h,t,s,Array.prototype.slice.call(a,1))}return p}if("ReactCompositeComponent"!==e||"mountComponent"!==t&&"updateComponent"!==t&&"_renderValidatedComponent"!==t)return n.apply(this,a);if(this._currentElement.type===u.TopLevelWrapper)return n.apply(this,a);var v="mountComponent"===t?a[0]:this._rootNodeID,m="_renderValidatedComponent"===t,y="mountComponent"===t,g=c._mountStack,b=c._allMeasurements[c._allMeasurements.length-1];if(m?o(b.counts,v,1):y&&(b.created[v]=!0,g.push(0)),d=l(),p=n.apply(this,a),s=l()-d,m)o(b.render,v,s);else if(y){var _=g.pop();g[g.length-1]+=s,o(b.exclusive,v,s-_),o(b.inclusive,v,s)}else o(b.inclusive,v,s);return b.displayNames[v]={current:this.getName(),owner:this._currentElement._owner?this._currentElement._owner.getName():"<root>"},p}}};e.exports=c},function(e,t,n){"use strict";function r(e){for(var t=0,n=0;n<e.length;n++){var r=e[n];t+=r.totalTime}return t}function o(e){var t=[];return e.forEach(function(e){Object.keys(e.writes).forEach(function(n){e.writes[n].forEach(function(e){t.push({id:n,type:c[e.type]||e.type,args:e.args})})})}),t}function a(e){for(var t,n={},r=0;r<e.length;r++){var o=e[r],a=s({},o.exclusive,o.inclusive);for(var i in a)t=o.displayNames[i].current,n[t]=n[t]||{componentName:t,inclusive:0,exclusive:0,render:0,count:0},o.render[i]&&(n[t].render+=o.render[i]),o.exclusive[i]&&(n[t].exclusive+=o.exclusive[i]),o.inclusive[i]&&(n[t].inclusive+=o.inclusive[i]),o.counts[i]&&(n[t].count+=o.counts[i])}var u=[];for(t in n)n[t].exclusive>=l&&u.push(n[t]);return u.sort(function(e,t){return t.exclusive-e.exclusive}),u}function i(e,t){for(var n,r={},o=0;o<e.length;o++){var a,i=e[o],c=s({},i.exclusive,i.inclusive);t&&(a=u(i));for(var p in c)if(!t||a[p]){var d=i.displayNames[p];n=d.owner+" > "+d.current,r[n]=r[n]||{componentName:n,time:0,count:0},i.inclusive[p]&&(r[n].time+=i.inclusive[p]),i.counts[p]&&(r[n].count+=i.counts[p])}}var f=[];for(n in r)r[n].time>=l&&f.push(r[n]);return f.sort(function(e,t){return t.time-e.time}),f}function u(e){var t={},n=Object.keys(e.writes),r=s({},e.exclusive,e.inclusive);for(var o in r){for(var a=!1,i=0;i<n.length;i++)if(0===n[i].indexOf(o)){a=!0;break}e.created[o]&&(a=!0),!a&&e.counts[o]>0&&(t[o]=!0)}return t}var s=n(40),l=1.2,c={_mountImageIntoNode:"set innerHTML",INSERT_MARKUP:"set innerHTML",MOVE_EXISTING:"move",REMOVE_NODE:"remove",SET_MARKUP:"set innerHTML",TEXT_CONTENT:"set textContent",setValueForProperty:"update attribute",setValueForAttribute:"update attribute",deleteValueForProperty:"remove attribute",setValueForStyles:"update styles",replaceNodeWithMarkup:"replace",updateTextContent:"set textContent"},p={getExclusiveSummary:a,getInclusiveSummary:i,getDOMSummary:o,getTotalTime:r};e.exports=p},function(e,t,n){"use strict";var r,o=n(146);r=o.now?function(){return o.now()}:function(){return Date.now()},e.exports=r},function(e,t,n){"use strict";var r,o=n(10);o.canUseDOM&&(r=window.performance||window.msPerformance||window.webkitPerformance),e.exports=r||{}},function(e,t){"use strict";e.exports="0.14.8"},function(e,t,n){"use strict";var r=n(29);e.exports=r.renderSubtreeIntoContainer},function(e,t,n){"use strict";var r=n(72),o=n(150),a=n(147);r.inject();var i={renderToString:o.renderToString,renderToStaticMarkup:o.renderToStaticMarkup,version:a};e.exports=i},function(e,t,n){(function(t){"use strict";function r(e){i.isValidElement(e)?void 0:"production"!==t.env.NODE_ENV?h(!1,"renderToString(): You must pass a valid ReactElement."):h(!1);var n;try{p.injection.injectBatchingStrategy(l);var r=u.createReactRootID();return n=c.getPooled(!1),n.perform(function(){var t=f(e,null),o=t.mountComponent(r,n,d);return s.addChecksumToMarkup(o)},null)}finally{c.release(n),p.injection.injectBatchingStrategy(a)}}function o(e){i.isValidElement(e)?void 0:"production"!==t.env.NODE_ENV?h(!1,"renderToStaticMarkup(): You must pass a valid ReactElement."):h(!1);var n;try{p.injection.injectBatchingStrategy(l);var r=u.createReactRootID();return n=c.getPooled(!0),n.perform(function(){var t=f(e,null);return t.mountComponent(r,n,d)},null)}finally{c.release(n),p.injection.injectBatchingStrategy(a)}}var a=n(93),i=n(43),u=n(46),s=n(49),l=n(151),c=n(152),p=n(55),d=n(59),f=n(63),h=n(14);e.exports={renderToString:r,renderToStaticMarkup:o}}).call(t,n(5))},function(e,t){"use strict";var n={isBatchingUpdates:!1,batchedUpdates:function(e){}};e.exports=n},function(e,t,n){"use strict";function r(e){this.reinitializeTransaction(),this.renderToStaticMarkup=e,this.reactMountReady=a.getPooled(null),this.useCreateElement=!1}var o=n(57),a=n(56),i=n(58),u=n(40),s=n(16),l={initialize:function(){this.reactMountReady.reset()},close:s},c=[l],p={getTransactionWrappers:function(){return c},getReactMountReady:function(){return this.reactMountReady},destructor:function(){a.release(this.reactMountReady),this.reactMountReady=null}};u(r.prototype,i.Mixin,p),o.addPoolingTo(r),e.exports=r},function(e,t,n){(function(t){"use strict";var r=n(111),o=n(124),a=n(123),i=n(154),u=n(43),s=n(155),l=n(108),c=n(147),p=n(40),d=n(157),f=u.createElement,h=u.createFactory,v=u.cloneElement;"production"!==t.env.NODE_ENV&&(f=s.createElement,h=s.createFactory,v=s.cloneElement);var m={Children:{map:r.map,forEach:r.forEach,count:r.count,toArray:r.toArray,only:d},Component:o,createElement:f,cloneElement:v,isValidElement:u.isValidElement,PropTypes:l,createClass:a.createClass,createFactory:h,createMixin:function(e){return e},DOM:i,version:c,__spread:p};e.exports=m}).call(t,n(5))},function(e,t,n){(function(t){"use strict";function r(e){return"production"!==t.env.NODE_ENV?a.createFactory(e):o.createFactory(e)}var o=n(43),a=n(155),i=n(156),u=i({a:"a",abbr:"abbr",address:"address",area:"area",article:"article",aside:"aside",audio:"audio",b:"b",base:"base",bdi:"bdi",bdo:"bdo",big:"big",blockquote:"blockquote",body:"body",br:"br",button:"button",canvas:"canvas",caption:"caption",cite:"cite",code:"code",col:"col",colgroup:"colgroup",data:"data",datalist:"datalist",dd:"dd",del:"del",details:"details",dfn:"dfn",dialog:"dialog",div:"div",dl:"dl",dt:"dt",em:"em",embed:"embed",fieldset:"fieldset",figcaption:"figcaption",figure:"figure",footer:"footer",form:"form",h1:"h1",h2:"h2",h3:"h3",h4:"h4",h5:"h5",h6:"h6",head:"head",header:"header",hgroup:"hgroup",hr:"hr",html:"html",i:"i",iframe:"iframe",img:"img",input:"input",ins:"ins",kbd:"kbd",keygen:"keygen",label:"label",legend:"legend",li:"li",link:"link",main:"main",map:"map",mark:"mark",menu:"menu",menuitem:"menuitem",meta:"meta",meter:"meter",nav:"nav",noscript:"noscript",object:"object",ol:"ol",optgroup:"optgroup",option:"option",output:"output",p:"p",param:"param",picture:"picture",pre:"pre",progress:"progress",q:"q",rp:"rp",rt:"rt",ruby:"ruby",s:"s",samp:"samp",script:"script",section:"section",select:"select",small:"small",source:"source",span:"span",strong:"strong",style:"style",sub:"sub",summary:"summary",sup:"sup",table:"table",tbody:"tbody",td:"td",textarea:"textarea",tfoot:"tfoot",th:"th",thead:"thead",time:"time",title:"title",tr:"tr",track:"track",u:"u",ul:"ul","var":"var",video:"video",wbr:"wbr",circle:"circle",clipPath:"clipPath",defs:"defs",ellipse:"ellipse",g:"g",image:"image",line:"line",linearGradient:"linearGradient",mask:"mask",path:"path",pattern:"pattern",polygon:"polygon",polyline:"polyline",radialGradient:"radialGradient",rect:"rect",stop:"stop",svg:"svg",text:"text",tspan:"tspan"},r);e.exports=u}).call(t,n(5))},function(e,t,n){(function(t){"use strict";function r(){if(d.current){var e=d.current.getName();if(e)return" Check the render method of `"+e+"`."}return""}function o(e,n){if(e._store&&!e._store.validated&&null==e.key){e._store.validated=!0;var r=a("uniqueKey",e,n);null!==r&&("production"!==t.env.NODE_ENV?m(!1,'Each child in an array or iterator should have a unique "key" prop.%s%s%s',r.parentOrOwner||"",r.childOwner||"",r.url||""):void 0)}}function a(e,t,n){var o=r();if(!o){var a="string"==typeof n?n:n.displayName||n.name;a&&(o=" Check the top-level render call using <"+a+">.")}var i=y[e]||(y[e]={});if(i[o])return null;i[o]=!0;var u={parentOrOwner:o,url:" See https://fb.me/react-warning-keys for more information.",childOwner:null};return t&&t._owner&&t._owner!==d.current&&(u.childOwner=" It was passed a child from "+t._owner.getName()+"."),u}function i(e,t){if("object"==typeof e)if(Array.isArray(e))for(var n=0;n<e.length;n++){var r=e[n];l.isValidElement(r)&&o(r,t)}else if(l.isValidElement(e))e._store&&(e._store.validated=!0);else if(e){var a=h(e);if(a&&a!==e.entries)for(var i,u=a.call(e);!(i=u.next()).done;)l.isValidElement(i.value)&&o(i.value,t)}}function u(e,n,o,a){for(var i in n)if(n.hasOwnProperty(i)){var u;try{"function"!=typeof n[i]?"production"!==t.env.NODE_ENV?v(!1,"%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.",e||"React class",p[a],i):v(!1):void 0,u=n[i](o,i,e,a)}catch(s){u=s}if("production"!==t.env.NODE_ENV?m(!u||u instanceof Error,"%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",e||"React class",p[a],i,typeof u):void 0,u instanceof Error&&!(u.message in g)){g[u.message]=!0;var l=r();"production"!==t.env.NODE_ENV?m(!1,"Failed propType: %s%s",u.message,l):void 0}}}function s(e){var n=e.type;if("function"==typeof n){var r=n.displayName||n.name;n.propTypes&&u(r,n.propTypes,e.props,c.prop),"function"==typeof n.getDefaultProps&&("production"!==t.env.NODE_ENV?m(n.getDefaultProps.isReactClassApproved,"getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead."):void 0)}}var l=n(43),c=n(66),p=n(67),d=n(6),f=n(44),h=n(109),v=n(14),m=n(26),y={},g={},b={createElement:function(e,n,o){var a="string"==typeof e||"function"==typeof e;"production"!==t.env.NODE_ENV?m(a,"React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components).%s",r()):void 0;var u=l.createElement.apply(this,arguments);if(null==u)return u;if(a)for(var c=2;c<arguments.length;c++)i(arguments[c],e);return s(u),u},createFactory:function(e){var n=b.createElement.bind(null,e);return n.type=e,"production"!==t.env.NODE_ENV&&f&&Object.defineProperty(n,"type",{enumerable:!1,get:function(){return"production"!==t.env.NODE_ENV?m(!1,"Factory.type is deprecated. Access the class directly before passing it to createFactory."):void 0,Object.defineProperty(this,"type",{value:e}),e}}),n},cloneElement:function(e,t,n){for(var r=l.cloneElement.apply(this,arguments),o=2;o<arguments.length;o++)i(arguments[o],r.type);return s(r),r}};e.exports=b}).call(t,n(5))},function(e,t){"use strict";function n(e,t,n){if(!e)return null;var o={};for(var a in e)r.call(e,a)&&(o[a]=t.call(n,e[a],a,e));return o}var r=Object.prototype.hasOwnProperty;e.exports=n},function(e,t,n){(function(t){"use strict";function r(e){return o.isValidElement(e)?void 0:"production"!==t.env.NODE_ENV?a(!1,"onlyChild must be passed a children with exactly one child."):a(!1),e}var o=n(43),a=n(14);e.exports=r}).call(t,n(5))},function(e,t,n){(function(t){"use strict";function r(e,n,r,i,u){var s=!1;if("production"!==t.env.NODE_ENV){var l=function(){return"production"!==t.env.NODE_ENV?a(s,"React.%s is deprecated. Please use %s.%s from require('%s') instead.",e,n,e,r):void 0,s=!0,u.apply(i,arguments)};return o(l,u)}return u}var o=n(40),a=n(26);e.exports=r}).call(t,n(5))},function(e,t,n){var r,o;/*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ !function(){"use strict";function n(){for(var e=[],t=0;t<arguments.length;t++){var r=arguments[t];if(r){var o=typeof r;if("string"===o||"number"===o)e.push(r);else if(Array.isArray(r))e.push(n.apply(null,r));else if("object"===o)for(var i in r)a.call(r,i)&&r[i]&&e.push(i)}}return e.join(" ")}var a={}.hasOwnProperty;"undefined"!=typeof e&&e.exports?e.exports=n:(r=[],o=function(){return n}.apply(t,r),!(void 0!==o&&(e.exports=o)))}()},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(2),a=r(o),i=n(161),u=n(162),s=["lg","md","sm","xs"],l=["default","primary","link","inverse","success","warning","danger","info"],c={propTypes:{size:a["default"].PropTypes.oneOf(s),shape:a["default"].PropTypes.oneOf(l)},getClassNames:function(){var e=[],t=this.props,n=t.shape,r=t.size;return n&&e.push(this.prefix(n)),r&&e.push(this.prefix(r)),e},prefix:function p(e){var t=this.props.classPrefix,p=t?t+"-":"";return p+e},hasClass:function(e){var t=arguments.length<=1||void 0===arguments[1]?(0,i.findDOMNode)(this):arguments[1];return(0,u.hasClass)(t,e)},addClass:function(e){var t=arguments.length<=1||void 0===arguments[1]?(0,i.findDOMNode)(this):arguments[1];return(0,u.addClass)(t,e)},removeClass:function(e){var t=arguments.length<=1||void 0===arguments[1]?(0,i.findDOMNode)(this):arguments[1];return(0,u.removeClass)(t,e)},toggleClass:function(e){var t=arguments.length<=1||void 0===arguments[1]?(0,i.findDOMNode)(this):arguments[1],n=this.hasClass(e,t)?"removeClass":"addClass";return this[n](e,t)}};t["default"]=c},function(e,t,n){"use strict";e.exports=n(4)},function(e,t){"use strict";function n(e,t){return e.classList?!!t&&e.classList.contains(t):(" "+e.className+" ").indexOf(" "+t+" ")>-1}function r(e,t){return t&&(e.classList?e.classList.add(t):n(t,e)||(e.className=e.className+" "+t)),e}function o(e,t){return t&&(e.classList?e.classList.remove(t):n(t,e)&&(e.className=e.className.replace(new RegExp("(^|\\s)"+t+"(?:\\s|$)","g"),"$1").replace(/\s+/g," ").replace(/^\s*|\s*$/g,""))),e}Object.defineProperty(t,"__esModule",{value:!0}),t.hasClass=n,t.addClass=r,t.removeClass=o},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function a(e){return!e||"#"===e.trim()}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=n(2),s=r(u),l=n(164),c=r(l),p=s["default"].createClass({displayName:"Anchor",propTypes:{href:s["default"].PropTypes.string,onClick:s["default"].PropTypes.func,disabled:s["default"].PropTypes.bool,role:s["default"].PropTypes.string,componentClass:c["default"],tabIndex:s["default"].PropTypes.oneOfType([s["default"].PropTypes.number,s["default"].PropTypes.string])},getDefaultProps:function(){return{componentClass:"a",disabled:!1}},handleClick:function(e){var t=this.props,n=t.disabled,r=t.href,o=t.onClick;return(n||a(r))&&e.preventDefault(),n?void e.stopPropagation():void(o&&o(e))},render:function(){var e=this.props,t=e.componentClass,n=e.href,r=e.role,u=e.tabIndex,l=e.disabled,c=e.style,p=o(e,["componentClass","href","role","tabIndex","disabled","style"]);return a(n)&&(r=r||"button",n=n||""),l&&(u=-1,c=i({pointerEvents:"none"},c)),s["default"].createElement(t,i({},p,{role:r,href:n,style:c,tabIndex:u,onClick:this.handleClick}))}});t["default"]=p},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){if("function"!=typeof e[t]){var r=void 0;if(i["default"].isValidElement(e[t])&&(r="Invalid prop `{0}` of value `{1}` supplied to `{2}`. Expected an Element `type` , not an actual Element"),"string"!=typeof e[t]&&(r="Invalid prop `{0}` of value `{1}` supplied to `{2}`. Expected an Element `type` , such as a tag name or return value of React.createClass(...)"),r)return new Error((0,l.merge)(r,t,e[t],n))}}Object.defineProperty(t,"__esModule",{value:!0});var a=n(2),i=r(a),u=n(165),s=r(u),l=n(166);t["default"]=(0,s["default"])(o)},function(e,t){"use strict";function n(e){function t(t,n,r,o){return o=o||"<<anonymous>>",null!=n[r]?e(n,r,o):t?new Error("Required prop '"+r+"' was not specified in '"+o+"'."):void 0}var n=t.bind(null,!1);return n.isRequired=t.bind(null,!0),n}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n},function(e,t){"use strict";function n(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase()}function r(e){return e.replace(/\-(\w)/g,function(e){return e.slice(1).toUpperCase()})}function o(e){return e.replace(/([A-Z])/g,"-$1").toLowerCase()}function a(e){var t,n=0;for(t=1;t<arguments.length;t++)e=e.split("{"+n+"}").join(arguments[t]),n++;return e}Object.defineProperty(t,"__esModule",{value:!0}),t.underscore=n,t.camelize=r,t.hyphenate=o,t.merge=a,t["default"]={merge:a,underscore:n,camelize:r}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__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},i=n(2),u=r(i),s=n(159),l=r(s),c=u["default"].createClass({displayName:"ButtonToolbar",render:function(){var e=this.props,t=e.children,n=e.className,r=o(e,["children","className"]),i=(0,l["default"])({"btn-toolbar":!0},n);return u["default"].createElement("div",a({role:"toolbar",className:i},r),t)}});t["default"]=c},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var 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},i=n(2),u=r(i),s=n(159),l=r(s),c=n(160),p=r(c),d=n(169),f=r(d),h=n(171),v=r(h),m=n(172),y=r(m),g=n(173),b=r(g),_=n(164),E=r(_),N=n(174),O=r(N),C=u["default"].createClass({displayName:"Dropdown",mixins:[p["default"]],propTypes:{active:u["default"].PropTypes.bool,disabled:u["default"].PropTypes.bool,block:u["default"].PropTypes.bool,dropup:u["default"].PropTypes.bool,role:u["default"].PropTypes.string,onClose:u["default"].PropTypes.func,onOpen:u["default"].PropTypes.func,onToggle:u["default"].PropTypes.func,onSelect:u["default"].PropTypes.func,componentClass:E["default"],select:u["default"].PropTypes.bool,activeKey:u["default"].PropTypes.any},getDefaultProps:function(){return{componentClass:f["default"],active:!1,disabled:!1,block:!1}},getInitialState:function(){return{title:null,activeKey:this.props.activeKey,open:!1}},toggle:function(e){var t=e||!this.state.open,n=t?this.props.onOpen:this.props.onClose;this.setState({open:t},function(){n&&n()}),this.props.onToggle&&this.props.onToggle()},handleClick:function(){this.props.disabled||this.toggle()},handleSelect:function(e,t,n){this.props.select&&this.setState({title:t.children,activeKey:t.eventKey}),this.props.onSelect&&this.props.onSelect(e,t,n)},componentWillMount:function(){var e=this,t=this.props,n=t.children,r=t.select,o=t.activeKey,a=void 0;r&&u["default"].Children.map(n,function(t,n){o===t.props.eventKey?a=t.props.children:t.props.active&&(a=t.props.children),a&&e.setState({title:a})})},render:function(){var e=this.props,t=(e.items,e.title),n=e.children,r=e.className,i=(e.activeKey,e.dropup),s=e.componentClass,c=o(e,["items","title","children","className","activeKey","dropup","componentClass"]),p=u["default"].createElement(v["default"],a({},c,{onClick:this.handleClick}),this.state.title||t),d=u["default"].createElement(y["default"],{onClose:this.toggle,onSelect:this.handleSelect,activeKey:this.state.activeKey,ref:"menu"},n);this.state.open&&(d=u["default"].createElement(O["default"],{onRootClose:this.toggle},d));var f=(0,l["default"])({dropdown:!i,dropup:i,open:this.state.open},r);return u["default"].createElement(s,a({},c,{className:f,role:"dropdown"}),p,d)}});C.Item=b["default"],t["default"]=C},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=n(2),s=r(u),l=n(161),c=n(159),p=r(c),d=n(160),f=r(d),h=n(170),v=r(h),m=s["default"].createClass({displayName:"ButtonGroup",mixins:[f["default"]],propTypes:{type:s["default"].PropTypes.oneOf(["radio","checkbox"]),classPrefix:s["default"].PropTypes.string,vertical:s["default"].PropTypes.bool,justified:s["default"].PropTypes.bool,block:s["default"].PropTypes.bool,onClick:s["default"].PropTypes.func},getDefaultProps:function(){return{block:!1,justified:!1,vertical:!1,classPrefix:"btn-group"}},handleClick:function(e){var t=e.target,n=this.props.type,r=this.refs;if("checkbox"===n)this.toggleClass("active",t);else if("radio"===n)for(var o in r){var a=(0,l.findDOMNode)(r[o]),i=t===a?"addClass":"removeClass";r[o][i]("active")}},render:function(){var e,t=this.props,n=t.children,r=t.className,u=t.vertical,l=t.block,c=t.justified,d=p["default"].apply(void 0,[(e={"btn-group":!0,"btn-block":l},o(e,this.prefix("vertical"),u),o(e,this.prefix("justified"),c),e)].concat(a(this.getClassNames()),[r])),f=s["default"].Children.map(n,function(e,t){return s["default"].cloneElement(e,{key:t,ref:"btn_"+t},e.props.children)});return s["default"].createElement("div",i({},this.props,{className:d,onClick:(0,v["default"])(this.handleClick,this.props.onClick)}),f)}});t["default"]=m},function(e,t){"use strict";function n(){for(var e=arguments.length,t=Array(e),n=0;e>n;n++)t[n]=arguments[n];return t.filter(function(e){return null!=e}).reduce(function(e,t){if("function"!=typeof t)throw new Error("Invalid Argument Type, must only provide functions, undefined, or null.");return null===e?t:function(){for(var n=arguments.length,r=Array(n),o=0;n>o;o++)r[o]=arguments[o];e.apply(this,r),t.apply(this,r)}},null)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Object.defineProperty(t,"__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},i=n(2),u=r(i),s=n(159),l=r(s),c=n(1),p=r(c),d=n(164),f=(r(d),u["default"].createElement("span",null," ",u["default"].createElement("span",{className:"caret"}))),h=u["default"].createClass({displayName:"DorpdownToggle",propTypes:{noCaret:u["default"].PropTypes.bool,open:u["default"].PropTypes.bool,title:u["default"].PropTypes.string,useAnchor:u["default"].PropTypes.bool},getDefaultProps:function(){return{open:!1,noCaret:!1,useAnchor:!1}},render:function(){var e=this.props.noCaret?null:f,t=this.props.useAnchor?"a":p["default"],n=o({},"dropdown-toggle",!0);return u["default"].createElement(t,a({},this.props,{className:(0,l["default"])(n,this.props.className),type:"button",role:"toggle"}),this.props.title||this.props.children,e)}});t["default"]=h},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=n(2),s=r(u),l=(n(161),n(159)),c=r(l),p=n(173),d=(r(p),n(160)),f=r(d),h=n(170),v=r(h),m=s["default"].createClass({displayName:"DorpdownMenu",mixins:[f["default"]],propTypes:{pullRight:s["default"].PropTypes.bool,onClose:s["default"].PropTypes.func,onSelect:s["default"].PropTypes.func},getDefaultProps:function(){return{classPrefix:"dropdown",pullRight:!1}},getFocusableMenuItems:function(){var e=ReactDOM.findDOMNode(this);return void 0===e?[]:Array.from(e.querySelectorAll('[role="menu-item"]'))},getItemsAndActiveIndex:function(){var e=this.getFocusableMenuItems(),t=e.indexOf(document.activeElement);return{items:e,activeItemIndex:t}},handleSelect:function(e){var t=this.props.onClose;t&&t()},render:function(){var e,t=this,n=this.props,r=n.pullRight,u=n.children,l=n.className,p=n.activeKey,d=a(n,["pullRight","children","className","activeKey"]),f=s["default"].Children.map(u,function(e,n){var r={key:n,ref:"menu_item_"+n,onSelect:(0,v["default"])(t.handleSelect,t.props.onSelect)};return p&&(r.active=p===e.props.eventKey),s["default"].cloneElement(e,r,e.props.children)}),h=(e={},o(e,this.prefix("menu"),!0),o(e,this.prefix("menu-right"),r),e);return s["default"].createElement("ul",i({},d,{className:(0,c["default"])(l,h),role:"menu"}),f)}});t["default"]=m},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var 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},i=n(2),u=r(i),s=n(159),l=r(s),c=n(160),p=r(c),d=n(164),f=r(d),h=u["default"].createClass({displayName:"DropdownMenuItem",mixins:[p["default"]],propTypes:{href:u["default"].PropTypes.string,divider:u["default"].PropTypes.bool,active:u["default"].PropTypes.bool,disabled:u["default"].PropTypes.bool,onSelect:u["default"].PropTypes.func,onKeyDown:u["default"].PropTypes.func,eventKey:u["default"].PropTypes.any,componentClass:f["default"]},getDefaultProps:function(){return{componentClass:"a",active:!1,disabled:!1,divider:!1}},handleClick:function(e){var t=this.props.onSelect;return this.props.disabled?void e.preventDefault():void(t&&t(this.props.eventKey,this.props,e))},render:function(){var e=this.props,t=e.children,n=e.divider,r=(e.onSelect,e.onKeyDown,e.componentClass),i=o(e,["children","divider","onSelect","onKeyDown","componentClass"]),s=(0,l["default"])({active:this.props.active,disabled:this.props.disabled});return n?u["default"].createElement("li",{role:"separator",className:"divider"}):u["default"].createElement("li",{role:"presentation",className:s},u["default"].createElement(r,a({},i,{role:"menu-item",tabIndex:"-1",onClick:this.handleClick}),t))}});t["default"]=h},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){return 0===e.button}function a(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function i(){var e="__click_was_inside_"+f++;return{id:e,suppressRootClose:function(t){t.nativeEvent[e]=!0}}}Object.defineProperty(t,"__esModule",{value:!0});var u=n(2),s=r(u),l=n(161),c=r(l),p=n(175),d=r(p),f=0,h=s["default"].createClass({displayName:"RootCloseWrapper",propTypes:{onRootClose:s["default"].PropTypes.func.isRequired},componentWillMount:function(){var e=i(),t=e.id,n=e.suppressRootClose;this._suppressRootId=t,this._suppressRootCloseHandler=n},componentDidMount:function(){this.bindRootCloseHandlers()},componentWillUnmount:function(){this.unbindRootCloseHandlers()},bindRootCloseHandlers:function(){var e=window.document;this._onDocumentClickListener=d["default"].on(e,"click",this.handleDocumentClick),this._onDocumentKeyupListener=d["default"].on(e,"keyup",this.handleDocumentKeyUp)},handleDocumentClick:function(e){e[this._suppressRootId]||!a(e)&&o(e)&&this.props.onRootClose()},handleDocumentKeyUp:function(e){27===e.keyCode&&this.props.onRootClose()},unbindRootCloseHandlers:function(){this._onDocumentClickListener&&this._onDocumentClickListener.off(),this._onDocumentKeyupListener&&this._onDocumentKeyupListener.off()},getWrappedDOMNode:function(){return c["default"].findDOMNode(this)},render:function(){var e=this.props.children,t=s["default"].Children.only(e);return s["default"].cloneElement(t,{onClick:this._suppressRootCloseHandler||t.props.onClick})}});t["default"]=h},function(e,t){"use strict";function n(e,t,n){var r=arguments.length<=3||void 0===arguments[3]?!1:arguments[3];return e[a](u+t,n,r),{off:function(){e[i](u+t,n,r)}}}function r(e,t,n){var r=arguments.length<=3||void 0===arguments[3]?!1:arguments[3];e[i](u+t,n,r)}function o(e){var t=!document.addEventListener,n=void 0;return t?(document.attachEvent("onfocusin",e),n=function(){return document.detachEvent("onfocusin",e)}):(document.addEventListener("focus",e,!0),n=function(){return document.removeEventListener("focus",e,!0)}),{off:n}}Object.defineProperty(t,"__esModule",{value:!0});var a=window.addEventListener?"addEventListener":"attachEvent",i=window.removeEventListener?"removeEventListener":"detachEvent",u="addEventListener"!==a?"on":"";t["default"]={on:n,onFocus:o,off:r}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){return Array.isArray(t)?t.indexOf(e)>=0:e===t}function a(e){return(0,v.isNull)(e)||(0,v.isUndefined)(e)}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=n(2),s=r(u),l=n(161),c=r(l),p=n(177),d=r(p),f=n(179),h=r(f),v=n(189),m=n(170),y=r(m),g=s["default"].createClass({displayName:"Whisper",propTypes:i({},h["default"].propTypes,{trigger:s["default"].PropTypes.oneOfType([s["default"].PropTypes.oneOf(["click","hover","focus"]),s["default"].PropTypes.arrayOf(s["default"].PropTypes.oneOf(["click","hover","focus"]))]),delay:s["default"].PropTypes.number,delayShow:s["default"].PropTypes.number,delayHide:s["default"].PropTypes.number,defaultOverlayShown:s["default"].PropTypes.bool,speaker:s["default"].PropTypes.node.isRequired,onBlur:s["default"].PropTypes.func,onClick:s["default"].PropTypes.func,onFocus:s["default"].PropTypes.func,onMouseLeave:s["default"].PropTypes.func,target:function(){},onHide:function(){},show:function(){}}),getDefaultProps:function(){return{defaultOverlayShown:!1,trigger:["hover","focus"],rootClose:!0}},getInitialState:function(){return{isOverlayShown:this.props.defaultOverlayShown}},show:function(){this.setState({isOverlayShown:!0})},hide:function(){this.setState({isOverlayShown:!1})},toggle:function(){this.state.isOverlayShown?this.hide():this.show()},componentWillMount:function(){this.handleMouseOver=this.handleMouseOverOut.bind(null,this.handleDelayedShow),this.handleMouseOut=this.handleMouseOverOut.bind(null,this.handleDelayedHide)},componentDidMount:function(){this._mountNode=document.createElement("div"),this.renderOverlay()},renderOverlay:function(){c["default"].unstable_renderSubtreeIntoContainer(this,this._speaker,this._mountNode)},componentWillUnmount:function(){c["default"].unmountComponentAtNode(this._mountNode),this._mountNode=null,clearTimeout(this._hoverShowDelay),clearTimeout(this._hoverHideDelay)},componentDidUpdate:function(){this._mountNode&&this.renderOverlay()},getOverlayTarget:function(){return c["default"].findDOMNode(this)},getOverlay:function(){var e=i({},(0,v.pick)(this.props,Object.keys(h["default"].propTypes)),{show:this.state.isOverlayShown,onHide:this.hide,target:this.getOverlayTarget,onExit:this.props.onExit,onExiting:this.props.onExiting,onExited:this.props.onExited,onEnter:this.props.onEnter,onEntering:this.props.onEntering,onEntered:this.props.onEntered}),t=(0,u.cloneElement)(this.props.speaker,{placement:e.placement,container:e.container});return s["default"].createElement(h["default"],e,t)},render:function(){var e=s["default"].Children.only(this.props.children),t=e.props,n={"aria-describedby":this.props.speaker.props.id};return this._speaker=this.getOverlay(),n.onClick=(0,y["default"])(t.onClick,this.props.onClick),o("click",this.props.trigger)&&(n.onClick=(0,y["default"])(this.toggle,n.onClick)),o("hover",this.props.trigger)&&(new Error(!("hover"===this.props.trigger),'[suite] Specifying only the `"hover"` trigger limits the visibilty of the speaker to just mouse users. Consider also including the `"focus"` trigger so that touch and keyboard only users can see the speaker as well.'),n.onMouseOver=(0,y["default"])(this.handleMouseOver,this.props.onMouseOver,t.onMouseOver),n.onMouseOut=(0,y["default"])(this.handleMouseOut,this.props.onMouseOut,t.onMouseOut)),o("focus",this.props.trigger)&&(n.onFocus=(0,y["default"])(this.handleDelayedShow,this.props.onFocus,t.onFocus),n.onBlur=(0,y["default"])(this.handleDelayedHide,this.props.onBlur,t.onBlur)),(0,u.cloneElement)(e,n)},handleDelayedShow:function(){var e=this;if(!a(this._hoverHideDelay))return clearTimeout(this._hoverHideDelay),void(this._hoverHideDelay=null);if(!this.state.isOverlayShown&&a(this._hoverShowDelay)){var t=a(this.props.delayShow)?this.props.delay:this.props.delayShow;return t?void(this._hoverShowDelay=setTimeout(function(){e._hoverShowDelay=null,e.show()},t)):void this.show()}},handleDelayedHide:function(){var e=this;if(!a(this._hoverShowDelay))return clearTimeout(this._hoverShowDelay),void(this._hoverShowDelay=null);if(this.state.isOverlayShown&&a(this._hoverHideDelay)){var t=a(this.props.delayHide)?this.props.delay:this.props.delayHide;return t?void(this._hoverHideDelay=setTimeout(function(){e._hoverHideDelay=null,e.hide()},t)):void this.hide()}},handleMouseOverOut:function(e,t){var n=t.currentTarget,r=t.relatedTarget||t.nativeEvent.toElement;r&&(r===n||d["default"].contains(n,r))||e(t)}});t["default"]=g},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=E["default"].findDOMNode(e);return t&&t.ownerDocument||document}function a(e){var t=o(e);return t&&t.defaultView||t.parentWindow}function i(e){return e===e.window?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}function u(e,t){return e="function"==typeof e?e():e,E["default"].findDOMNode(e)||t}function s(e){return e.nodeName&&e.nodeName.toLowerCase()}function l(e,t){var n=i(e),r=n?"pageYOffset"in n?n.pageYOffset:n.document.documentElement.scrollTop:e.scrollTop,o=n?"pageXOffset"in n?n.pageXOffset:n.document.documentElement.scrollLeft:0;return void 0===t?r:void(n?n.scrollTo(o,t):e.scrollTop=t)}function c(e,t){var n=i(e),r=n?"pageXOffset"in n?n.pageXOffset:n.document.documentElement.scrollLeft:e.scrollLeft,o=n?"pageYOffset"in n?n.pageYOffset:n.document.documentElement.scrollTop:0;return void 0===t?r:void(n?n.scrollTo(t,o):e.scrollLeft=t)}function p(e){var t=o(e),n=i(t),r=t&&t.documentElement,a={top:0,left:0,height:0,width:0};return t?C(r,e)?(void 0!==e.getBoundingClientRect&&(a=e.getBoundingClientRect()),(a.width||a.height)&&(a={top:a.top+(n.pageYOffset||r.scrollTop)-(r.clientTop||0),left:a.left+(n.pageXOffset||r.scrollLeft)-(r.clientLeft||0),width:(null===a.width?e.offsetWidth:a.width)||0,height:(null===a.height?e.offsetHeight:a.height)||0}),a):a:void 0}function d(e){for(var t=o(e),n=e&&e.offsetParent;n&&"html"!==s(e)&&"static"===(0,N.addStyle)(n,"position");)n=n.offsetParent;return n||t.documentElement}function f(e,t){var n,r={top:0,left:0};return"fixed"===(0,N.addStyle)(e,"position")?n=e.getBoundingClientRect():(t=t||offsetParent(e),n=offset(e),"html"!==s(t)&&(r=offset(t)),r.top+=parseInt((0,N.addStyle)(t,"borderTopWidth"),10)-l(t)||0,r.left+=parseInt((0,N.addStyle)(t,"borderLeftWidth"),10)-c(t)||0),b({},offset,{top:n.top-r.top-(parseInt((0,N.addStyle)(e,"marginTop"),10)||0),left:n.left-r.left-(parseInt((0,N.addStyle)(e,"marginLeft"),10)||0)})}function h(e){function t(e){var t=o(e),n=i(t),r=n.innerWidth;if(!r){var a=t.documentElement.getBoundingClientRect();r=a.right-Math.abs(a.left)}return t.body.clientWidth<r}var n=i(e),r=e&&"body"===e.tagName.toLowerCase();return n||r?t(e):e.scrollHeight>e.clientHeight}function v(){var e=arguments.length<=0||void 0===arguments[0]?document:arguments[0];return e.activeElement}function m(e){var t=void 0;if((!t||e)&&O){var n=document.createElement("div");n.style.position="absolute",n.style.top="-9999px",n.style.width="50px",n.style.height="50px",n.style.overflow="scroll",document.body.appendChild(n),t=n.offsetWidth-n.clientWidth,document.body.removeChild(n)}return t}function y(e,t){var n=i(e);return n?n.innerHeight:t?e.clientHeight:p(e).height}function g(e,t){var n=i(e);return n?n.innerWidth:t?e.clientWidth:p(e).width}Object.defineProperty(t,"__esModule",{value:!0}),t.contains=t.canUseDOM=void 0;var b=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t.ownerDocument=o,t.ownerWindow=a,t.getWindow=i,t.getContainer=u,t.nodeName=s,t.scrollTop=l,t.scrollLeft=c,t.getOffset=p,t.getOffsetParent=d,t.getPosition=f,t.isOverflowing=h,t.activeElement=v,t.getScrollbarSize=m,t.getHeight=y,t.getWidth=g;var _=n(161),E=r(_),N=n(178),O=t.canUseDOM=!("undefined"==typeof window||!window.document||!window.document.createElement),C=t.contains=function(){var e=O&&document.documentElement;return e&&e.contains?function(e,t){return e.contains(t)}:e&&e.compareDocumentPosition?function(e,t){return e===t||!!(16&e.compareDocumentPosition(t))}:function(e,t){if(t)do if(t===e)return!0;while(t=t.parentNode);return!1}}();t["default"]={ownerDocument:o,ownerWindow:a,getContainer:u,canUseDOM:O,contains:C,getOffset:p,getOffsetParent:d,getPosition:f,getHeight:y,getWidth:g,isOverflowing:h,activeElement:v,getScrollbarSize:m}},function(e,t,n){"use strict";function r(e){return(0,l.camelize)(e.replace(c,"ms-"))}function o(e){return(0,l.hyphenate)(e).replace(c,"-ms-")}function a(e){if(!e)throw new TypeError("No Element passed to `getComputedStyle()`");var t=e.ownerDocument;return"defaultView"in t?t.defaultView.opener?e.ownerDocument.defaultView.getComputedStyle(e,null):window.getComputedStyle(e,null):{getPropertyValue:function(t){var n=e.style;t=(0,l.camelize)(t),"float"===t&&(t="styleFloat");var r=e.currentStyle[t]||null;if(null===r&&n&&n[t]&&(r=n[t]),rnumnonpx.test(r)&&!rposition.test(t)){var o=n.left,a=e.runtimeStyle,i=a&&a.left;i&&(a.left=e.currentStyle.left),n.left="fontSize"===t?"1em":r,r=n.pixelLeft+"px",n.left=o,i&&(a.left=i)}return r}}}function i(e,t){return"removeProperty"in e.style?e.style.removeProperty(t):e.style.removeAttribute(t)}function u(e,t,n){var r="",a=t;if("string"==typeof t){if(void 0===n)return s(e,t);(a={})[t]=n}for(var u in a)Object.prototype.hasOwnProperty.call(a,u)&&(a[u]||0===a[u]?r+=o(u)+":"+a[u]+";":i(e,o(u)));e.style.cssText+=";"+r}function s(e,t){return e.style[r(t)]||a(e).getPropertyValue(o(t))}Object.defineProperty(t,"__esModule",{value:!0}),t.removeStyle=i,t.addStyle=u,t.getStyle=s;var l=n(166),c=/^ms-/;t["default"]={addStyle:u,removeStyle:i,getStyle:s}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__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},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}}(),c=n(2),p=r(c),d=n(159),f=r(d),h=n(164),v=r(h),m=n(180),y=r(m),g=n(185),b=r(g),_=function(e){function t(){return a(this,t),i(this,Object.getPrototypeOf(t).apply(this,arguments))}return u(t,e),l(t,[{key:"render",value:function(){var e=this.props,t=e.children,n=e.animation,r=o(e,["children","animation"]);return n===!0&&(n=b["default"]),n===!1&&(n=null),n||(t=(0,c.cloneElement)(t,{className:(0,f["default"])("in",t.props.className)})),p["default"].createElement(y["default"],s({},r,{transition:n}),t)}}]),t}(p["default"].Component);_.propTypes=s({},y["default"].propTypes,{show:p["default"].PropTypes.bool,rootClose:p["default"].PropTypes.bool,onHide:p["default"].PropTypes.func,animation:p["default"].PropTypes.oneOfType([p["default"].PropTypes.bool,v["default"]])}),_.defaultProps={animation:b["default"],rootClose:!1,show:!1},t["default"]=_},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__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},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}}(),c=n(2),p=r(c),d=n(181),f=r(d),h=n(183),v=r(h),m=n(174),y=r(m),g=n(164),b=r(g),_=function(e){function t(e,n){a(this,t);var r=i(this,Object.getPrototypeOf(t).call(this,e,n));return r.state={exited:!e.show},r.onHiddenListener=r.handleHidden.bind(r),r}return u(t,e),l(t,[{key:"componentWillReceiveProps",value:function(e){e.show?this.setState({exited:!1}):e.transition||this.setState({exited:!0})}},{key:"render",value:function(){var e=this.props,t=e.container,n=e.containerPadding,r=e.target,a=e.placement,i=e.shouldUpdatePosition,u=e.rootClose,s=e.children,l=e.transition,c=o(e,["container","containerPadding","target","placement","shouldUpdatePosition","rootClose","children","transition"]),d=c.show||l&&!this.state.exited;if(!d)return null;var h=s;if(h=p["default"].createElement(v["default"],{container:t,containerPadding:n,target:r,placement:a,shouldUpdatePosition:i},h),l){var m=c.onExit,g=c.onExiting,b=c.onEnter,_=c.onEntering,E=c.onEntered;h=p["default"].createElement(l,{"in":c.show,transitionAppear:!0,onExit:m,onExiting:g,onExited:this.onHiddenListener,onEnter:b,onEntering:_,onEntered:E},h)}return u&&(h=p["default"].createElement(y["default"],{onRootClose:c.onHide},h)),p["default"].createElement(f["default"],{ container:t},h)}},{key:"handleHidden",value:function(){if(this.setState({exited:!0}),this.props.onExited){var e;(e=this.props).onExited.apply(e,arguments)}}}]),t}(p["default"].Component);_.propTypes=s({},f["default"].propTypes,v["default"].propTypes,{show:p["default"].PropTypes.bool,rootClose:p["default"].PropTypes.bool,onHide:function(e,t,n){var r=p["default"].PropTypes.func;return e.rootClose&&(r=r.isRequired),r(e,t,n)},transition:b["default"],onEnter:p["default"].PropTypes.func,onEntering:p["default"].PropTypes.func,onEntered:p["default"].PropTypes.func,onExit:p["default"].PropTypes.func,onExiting:p["default"].PropTypes.func,onExited:p["default"].PropTypes.func}),t["default"]=_},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(2),a=r(o),i=n(161),u=r(i),s=n(182),l=r(s),c=n(177),p=a["default"].createClass({displayName:"Portal",propTypes:{container:a["default"].PropTypes.oneOfType([l["default"],a["default"].PropTypes.func])},componentDidMount:function(){this._renderOverlay()},componentDidUpdate:function(){this._renderOverlay()},componentWillReceiveProps:function(e){this._overlayTarget&&e.container!==this.props.container&&(this._portalContainerNode.removeChild(this._overlayTarget),this._portalContainerNode=(0,c.getContainer)(e.container,(0,c.ownerDocument)(this).body),this._portalContainerNode.appendChild(this._overlayTarget))},componentWillUnmount:function(){this._unrenderOverlay(),this._unmountOverlayTarget()},_mountOverlayTarget:function(){this._overlayTarget||(this._overlayTarget=document.createElement("div"),this._portalContainerNode=(0,c.getContainer)(this.props.container,(0,c.ownerDocument)(this).body),this._portalContainerNode.appendChild(this._overlayTarget))},_unmountOverlayTarget:function(){this._overlayTarget&&(this._portalContainerNode.removeChild(this._overlayTarget),this._overlayTarget=null),this._portalContainerNode=null},_renderOverlay:function(){var e=this.props.children?a["default"].Children.only(this.props.children):null;null!==e?(this._mountOverlayTarget(),this._overlayInstance=u["default"].unstable_renderSubtreeIntoContainer(this,e,this._overlayTarget)):(this._unrenderOverlay(),this._unmountOverlayTarget())},_unrenderOverlay:function(){this._overlayTarget&&(u["default"].unmountComponentAtNode(this._overlayTarget),this._overlayInstance=null)},render:function(){return null},getMountNode:function(){return this._overlayTarget},getOverlayDOMNode:function(){if(!this.isMounted())throw new Error("getOverlayDOMNode(): A component must be mounted to have a DOM node.");return this._overlayInstance?this._overlayInstance.getWrappedDOMNode?this._overlayInstance.getWrappedDOMNode():u["default"].findDOMNode(this._overlayInstance):null}});t["default"]=p},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return"object"!==a(e[t])||"function"!=typeof e[t].render&&1!==e[t].nodeType?new Error((0,s.merge)("Invalid prop `{0}` of value `{1}` supplied to `{2}` , expected a DOM element or an object that has a `render` method",t,e[t],n)):void 0}Object.defineProperty(t,"__esModule",{value:!0});var a="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},i=n(165),u=r(i),s=n(166);t["default"]=(0,u["default"])(o)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__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},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}}(),c=n(2),p=r(c),d=n(161),f=r(d),h=n(159),v=r(h),m=n(182),y=r(m),g=n(177),b=n(184),_=r(b),E=function(e){function t(e,n){a(this,t);var r=i(this,Object.getPrototypeOf(t).call(this,e,n));return r.state={positionLeft:0,positionTop:0,arrowOffsetLeft:null,arrowOffsetTop:null},r._needsFlush=!1,r._lastTarget=null,r}return u(t,e),l(t,[{key:"componentDidMount",value:function(){this.updatePosition()}},{key:"componentWillReceiveProps",value:function(){this._needsFlush=!0}},{key:"componentDidUpdate",value:function(e){this._needsFlush&&(this._needsFlush=!1,this.updatePosition(e.placement!==this.props.placement))}},{key:"componentWillUnmount",value:function(){this._lastTarget=null}},{key:"render",value:function(){var e=this.props,t=e.children,n=e.className,r=o(e,["children","className"]),a=this.state,i=a.positionLeft,u=a.positionTop,l=o(a,["positionLeft","positionTop"]);delete r.target,delete r.container,delete r.containerPadding;var d=p["default"].Children.only(t);return(0,c.cloneElement)(d,s({},r,l,{positionLeft:i,positionTop:u,className:(0,v["default"])(n,d.props.className),style:s({},d.props.style,{left:i,top:u})}))}},{key:"getTargetSafe",value:function(){if(!this.props.target)return null;var e=this.props.target(this.props);return e?e:null}},{key:"updatePosition",value:function(e){var t=this.getTargetSafe();if(this.props.shouldUpdatePosition||t!==this._lastTarget||e){if(this._lastTarget=t,!t)return void this.setState({positionLeft:0,positionTop:0,arrowOffsetLeft:null,arrowOffsetTop:null});var n=f["default"].findDOMNode(this),r=(0,g.getContainer)(this.props.container,(0,g.ownerDocument)(this).body);this.setState(_["default"].calcOverlayPosition(this.props.placement,n,t,r,this.props.containerPadding))}}}]),t}(p["default"].Component);E.propTypes={target:p["default"].PropTypes.func,container:p["default"].PropTypes.oneOfType([y["default"],p["default"].PropTypes.func]),containerPadding:p["default"].PropTypes.number,placement:p["default"].PropTypes.oneOf(["top","right","bottom","left"]),shouldUpdatePosition:p["default"].PropTypes.bool},E.displayName="Position",E.defaultProps={containerPadding:0,placement:"right",shouldUpdatePosition:!1},t["default"]=E},function(e,t,n){"use strict";function r(e,t,n,r){var o=i.getContainerDimensions(n),a=o.scroll,u=o.height,s=e-r-a,l=e+r-a+t;return 0>s?-s:l>u?u-l:0}function o(e,t,n,r){var o=i.getContainerDimensions(n),a=o.width,u=e-r,s=e+r+t;return 0>u?-u:s>a?a-s:0}Object.defineProperty(t,"__esModule",{value:!0});var a=n(177),i={getContainerDimensions:function(e){var t=void 0,n=void 0,r=void 0;if("BODY"===e.tagName)t=window.innerWidth,n=window.innerHeight,r=(0,a.scrollTop)((0,a.ownerDocument)(e).documentElement)||(0,a.scrollTop)(e);else{var o=(0,a.getOffset)(e);t=o.width,n=o.height,r=(0,a.scrollTop)(e)}return{width:t,height:n,scroll:r}},getPosition:function(e,t){var n="BODY"===t.tagName?(0,a.getOffset)(e):(0,a.getPosition)(e,t);return n},calcOverlayPosition:function(e,t,n,u,s){var l=i.getPosition(n,u),c=(0,a.getOffset)(t),p=c.height,d=c.width,f=void 0,h=void 0,v=void 0,m=void 0;if("left"===e||"right"===e){h=l.top+(l.height-p)/2,f="left"===e?l.left-d:l.left+l.width;var y=r(h,p,u,s);h+=y,m=50*(1-2*y/p)+"%",v=void 0}else{if("top"!==e&&"bottom"!==e)throw new Error('calcOverlayPosition(): No such placement of "'+e+'" found.');f=l.left+(l.width-d)/2,h="top"===e?l.top-p:l.top+l.height;var g=o(f,d,u,s);f+=g,v=50*(1-2*g/d)+"%",m=void 0}return{positionLeft:f,positionTop:h,arrowOffsetLeft:v,arrowOffsetTop:m}}};t["default"]=i},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function 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 i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),l=n(2),c=r(l),p=n(159),d=r(p),f=n(186),h=r(f),v=n(188),m=r(v),y=function(e){function t(){return o(this,t),a(this,Object.getPrototypeOf(t).apply(this,arguments))}return i(t,e),s(t,[{key:"render",value:function(){var e=this.props.timeout||this.props.duration;return c["default"].createElement(h["default"],u({},this.props,{timeout:e,className:(0,d["default"])(this.props.className,"fade"),enteredClassName:"in",enteringClassName:"in"}),this.props.children)}}]),t}(c["default"].Component);y.propTypes={"in":c["default"].PropTypes.bool,unmountOnExit:c["default"].PropTypes.bool,transitionAppear:c["default"].PropTypes.bool,timeout:c["default"].PropTypes.number,duration:(0,m["default"])(c["default"].PropTypes.number,"Use `timeout`."),onEnter:c["default"].PropTypes.func,onEntering:c["default"].PropTypes.func,onEntered:c["default"].PropTypes.func,onExit:c["default"].PropTypes.func,onExiting:c["default"].PropTypes.func,onExited:c["default"].PropTypes.func},y.defaultProps={"in":!1,timeout:300,unmountOnExit:!1,transitionAppear:!1},t["default"]=y},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function s(){}Object.defineProperty(t,"__esModule",{value:!0}),t.EXITING=t.ENTERED=t.ENTERING=t.EXITED=t.UNMOUNTED=void 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},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}}(),p=n(2),d=r(p),f=n(161),h=r(f),v=n(187),m=r(v),y=n(175),g=r(y),b=n(159),_=r(b),E=m["default"].end,N=t.UNMOUNTED=0,O=t.EXITED=1,C=t.ENTERING=2,P=t.ENTERED=3,w=t.EXITING=4,T=function(e){function t(e,n){a(this,t);var r=i(this,Object.getPrototypeOf(t).call(this,e,n)),o=void 0;return o=e["in"]?e.transitionAppear?O:P:e.unmountOnExit?N:O,r.state={status:o},r.nextCallback=null,r}return u(t,e),c(t,[{key:"componentDidMount",value:function(){this.props.transitionAppear&&this.props["in"]&&this.performEnter(this.props)}},{key:"componentWillReceiveProps",value:function(e){e["in"]&&this.props.unmountOnExit?this.state.status===N&&this.setState({status:O}):this._needsUpdate=!0}},{key:"componentDidUpdate",value:function(){var e=this.state.status;return this.props.unmountOnExit&&e===O?void(this.props["in"]?this.performEnter(this.props):this.setState({status:N})):void(this._needsUpdate&&(this._needsUpdate=!1,this.props["in"]?e===w?this.performEnter(this.props):e===O&&this.performEnter(this.props):e!==C&&e!==P||this.performExit(this.props)))}},{key:"componentWillUnmount",value:function(){this.cancelNextCallback()}},{key:"performEnter",value:function(e){var t=this;this.cancelNextCallback();var n=h["default"].findDOMNode(this);e.onEnter(n),this.safeSetState({status:C},function(){t.props.onEntering(n),t.onTransitionEnd(n,function(){t.safeSetState({status:P},function(){t.props.onEntered(n)})})})}},{key:"performExit",value:function(e){var t=this;this.cancelNextCallback();var n=h["default"].findDOMNode(this);e.onExit(n),this.safeSetState({status:w},function(){t.props.onExiting(n),t.onTransitionEnd(n,function(){t.safeSetState({status:O},function(){t.props.onExited(n)})})})}},{key:"cancelNextCallback",value:function(){null!==this.nextCallback&&(this.nextCallback.cancel(),this.nextCallback=null)}},{key:"safeSetState",value:function(e,t){this.setState(e,this.setNextCallback(t))}},{key:"setNextCallback",value:function(e){var t=this,n=!0;return this.nextCallback=function(r){n&&(n=!1,t.nextCallback=null,e(r))},this.nextCallback.cancel=function(){n=!1},this.nextCallback}},{key:"onTransitionEnd",value:function(e,t){this.setNextCallback(t),e?(g["default"].on(e,E,this.nextCallback),setTimeout(this.nextCallback,this.props.timeout)):setTimeout(this.nextCallback,0)}},{key:"render",value:function(){var e=this.state.status;if(e===N)return null;var n=this.props,r=n.children,a=n.className,i=o(n,["children","className"]);Object.keys(t.propTypes).forEach(function(e){return delete i[e]});var u=void 0;e===O?u=this.props.exitedClassName:e===C?u=this.props.enteringClassName:e===P?u=this.props.enteredClassName:e===w&&(u=this.props.exitingClassName);var s=d["default"].Children.only(r);return d["default"].cloneElement(s,l({},i,{className:(0,_["default"])(s.props.className,a,u)}))}}]),t}(d["default"].Component);T.propTypes={"in":d["default"].PropTypes.bool,unmountOnExit:d["default"].PropTypes.bool,transitionAppear:d["default"].PropTypes.bool,timeout:d["default"].PropTypes.number,exitedClassName:d["default"].PropTypes.string,exitingClassName:d["default"].PropTypes.string,enteredClassName:d["default"].PropTypes.string,enteringClassName:d["default"].PropTypes.string,onEnter:d["default"].PropTypes.func,onEntering:d["default"].PropTypes.func,onEntered:d["default"].PropTypes.func,onExit:d["default"].PropTypes.func,onExiting:d["default"].PropTypes.func,onExited:d["default"].PropTypes.func},T.displayName="Transition",T.defaultProps={"in":!1,unmountOnExit:!1,transitionAppear:!1,timeout:5e3,onEnter:s,onEntering:s,onEntered:s,onExit:s,onExiting:s,onExited:s},t["default"]=T},function(e,t,n){"use strict";function r(){var e,t="",n={O:"otransitionend",Moz:"transitionend",Webkit:"webkitTransitionEnd",ms:"MSTransitionEnd"},r=document.createElement("div");for(var o in n)if(l.call(n,o)&&void 0!==r.style[o+"TransitionProperty"]){t="-"+o.toLowerCase()+"-",e=n[o];break}return e||void 0===r.style.transitionProperty||(e="transitionend"),{end:e,prefix:t}}Object.defineProperty(t,"__esModule",{value:!0});var o,a,i,u,s=n(177),l=Object.prototype.hasOwnProperty,c="transform",p={};s.canUseDOM&&(p=r(),c=p.prefix+c,i=p.prefix+"transition-property",a=p.prefix+"transition-duration",u=p.prefix+"transition-delay",o=p.prefix+"transition-timing-function"),t["default"]={transform:c,end:p.end,property:i,timing:o,delay:u,duration:a}},function(e,t){"use strict";function n(e,t){return function(n,r,o){return null!==n[r]&&new Error('"'+r+'" property of "'+o+'" has been deprecated.\n'+t),e(n,r,o)}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n},function(e,t,n){var r;(function(e,o){(function(){function a(e,t){return e.set(t[0],t[1]),e}function i(e,t){return e.add(t),e}function u(e,t,n){var r=n.length;switch(r){case 0:return e.call(t);case 1:return e.call(t,n[0]);case 2:return e.call(t,n[0],n[1]);case 3:return e.call(t,n[0],n[1],n[2])}return e.apply(t,n)}function s(e,t,n,r){for(var o=-1,a=e.length;++o<a;){var i=e[o];t(r,i,n(i),e)}return r}function l(e,t){for(var n=-1,r=e.length,o=-1,a=t.length,i=Array(r+a);++n<r;)i[n]=e[n];for(;++o<a;)i[n++]=t[o];return i}function c(e,t){for(var n=-1,r=e.length;++n<r&&t(e[n],n,e)!==!1;);return e}function p(e,t){for(var n=e.length;n--&&t(e[n],n,e)!==!1;);return e}function d(e,t){for(var n=-1,r=e.length;++n<r;)if(!t(e[n],n,e))return!1;return!0}function f(e,t){for(var n=-1,r=e.length,o=0,a=[];++n<r;){var i=e[n];t(i,n,e)&&(a[o++]=i)}return a}function h(e,t){return!!e.length&&C(e,t,0)>-1}function v(e,t,n){for(var r=-1,o=e.length;++r<o;)if(n(t,e[r]))return!0;return!1}function m(e,t){for(var n=-1,r=e.length,o=Array(r);++n<r;)o[n]=t(e[n],n,e);return o}function y(e,t){for(var n=-1,r=t.length,o=e.length;++n<r;)e[o+n]=t[n];return e}function g(e,t,n,r){var o=-1,a=e.length;for(r&&a&&(n=e[++o]);++o<a;)n=t(n,e[o],o,e);return n}function b(e,t,n,r){var o=e.length;for(r&&o&&(n=e[--o]);o--;)n=t(n,e[o],o,e);return n}function _(e,t){for(var n=-1,r=e.length;++n<r;)if(t(e[n],n,e))return!0;return!1}function E(e,t,n){for(var r=-1,o=e.length;++r<o;){var a=e[r],i=t(a);if(null!=i&&(u===te?i===i:n(i,u)))var u=i,s=a}return s}function N(e,t,n,r){var o;return n(e,function(e,n,a){return t(e,n,a)?(o=r?n:e,!1):void 0}),o}function O(e,t,n){for(var r=e.length,o=n?r:-1;n?o--:++o<r;)if(t(e[o],o,e))return o;return-1}function C(e,t,n){if(t!==t)return K(e,n);for(var r=n-1,o=e.length;++r<o;)if(e[r]===t)return r;return-1}function P(e,t,n,r){for(var o=n-1,a=e.length;++o<a;)if(r(e[o],t))return o;return-1}function w(e,t){var n=e?e.length:0;return n?D(e,t)/n:De}function T(e,t,n,r,o){return o(e,function(e,o,a){n=r?(r=!1,e):t(n,e,o,a)}),n}function x(e,t){var n=e.length;for(e.sort(t);n--;)e[n]=e[n].value;return e}function D(e,t){for(var n,r=-1,o=e.length;++r<o;){var a=t(e[r]);a!==te&&(n=n===te?a:n+a)}return n}function M(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}function k(e,t){return m(t,function(t){return[t,e[t]]})}function S(e){return function(t){return e(t)}}function R(e,t){return m(t,function(t){return e[t]})}function I(e,t){for(var n=-1,r=e.length;++n<r&&C(t,e[n],0)>-1;);return n}function j(e,t){for(var n=e.length;n--&&C(t,e[n],0)>-1;);return n}function A(e){return e&&e.Object===Object?e:null}function V(e,t){if(e!==t){var n=null===e,r=e===te,o=e===e,a=null===t,i=t===te,u=t===t;if(e>t&&!a||!o||n&&!i&&u||r&&u)return 1;if(t>e&&!n||!u||a&&!r&&o||i&&o)return-1}return 0}function L(e,t,n){for(var r=-1,o=e.criteria,a=t.criteria,i=o.length,u=n.length;++r<i;){var s=V(o[r],a[r]);if(s){if(r>=u)return s;var l=n[r];return s*("desc"==l?-1:1)}}return e.index-t.index}function U(e,t){for(var n=e.length,r=0;n--;)e[n]===t&&r++;return r}function F(e){return function(t,n){var r;return t===te&&n===te?0:(t!==te&&(r=t),n!==te&&(r=r===te?n:e(r,n)),r)}}function B(e){return Sn[e]}function W(e){return Rn[e]}function H(e){return"\\"+An[e]}function K(e,t,n){for(var r=e.length,o=t+(n?0:-1);n?o--:++o<r;){var a=e[o];if(a!==a)return o}return-1}function q(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(n){}return t}function z(e,t){return e="number"==typeof e||It.test(e)?+e:-1,t=null==t?Te:t,e>-1&&e%1==0&&t>e}function Y(e){for(var t,n=[];!(t=e.next()).done;)n.push(t.value);return n}function G(e){var t=-1,n=Array(e.size);return e.forEach(function(e,r){n[++t]=[r,e]}),n}function $(e,t){for(var n=-1,r=e.length,o=0,a=[];++n<r;){var i=e[n];i!==t&&i!==ie||(e[n]=ie,a[o++]=n)}return a}function X(e){var t=-1,n=Array(e.size);return e.forEach(function(e){n[++t]=e}),n}function Q(e){if(!e||!wn.test(e))return e.length;for(var t=Cn.lastIndex=0;Cn.test(e);)t++;return t}function Z(e){return e.match(Cn)}function J(e){return In[e]}function ee(e){function t(e){if(iu(e)&&!Qc(e)&&!(e instanceof o)){if(e instanceof r)return e;if(fl.call(e,"__wrapped__"))return Qo(e)}return new r(e)}function n(){}function r(e,t){this.__wrapped__=e,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=te}function o(e){this.__wrapped__=e,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=Me,this.__views__=[]}function A(){var e=new o(this.__wrapped__);return e.__actions__=Gr(this.__actions__),e.__dir__=this.__dir__,e.__filtered__=this.__filtered__,e.__iteratees__=Gr(this.__iteratees__),e.__takeCount__=this.__takeCount__,e.__views__=Gr(this.__views__),e}function It(){if(this.__filtered__){var e=new o(this);e.__dir__=-1,e.__filtered__=!0}else e=this.clone(),e.__dir__*=-1;return e}function Lt(){var e=this.__wrapped__.value(),t=this.__dir__,n=Qc(e),r=0>t,o=n?e.length:0,a=Mo(0,o,this.__views__),i=a.start,u=a.end,s=u-i,l=r?u:i-1,c=this.__iteratees__,p=c.length,d=0,f=Ll(s,this.__takeCount__);if(!n||re>o||o==s&&f==s)return kr(e,this.__actions__);var h=[];e:for(;s--&&f>d;){l+=t;for(var v=-1,m=e[l];++v<p;){var y=c[v],g=y.iteratee,b=y.type,_=g(m);if(b==Ce)m=_;else if(!_){if(b==Oe)continue e;break e}}h[d++]=m}return h}function Ut(){}function Ft(e,t){return Wt(e,t)&&delete e[t]}function Bt(e,t){if($l){var n=e[t];return n===ae?te:n}return fl.call(e,t)?e[t]:te}function Wt(e,t){return $l?e[t]!==te:fl.call(e,t)}function Ht(e,t,n){e[t]=$l&&n===te?ae:n}function Kt(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function qt(){this.__data__={hash:new Ut,map:ql?new ql:[],string:new Ut}}function zt(e){var t=this.__data__;return Fo(e)?Ft("string"==typeof e?t.string:t.hash,e):ql?t.map["delete"](e):an(t.map,e)}function Yt(e){var t=this.__data__;return Fo(e)?Bt("string"==typeof e?t.string:t.hash,e):ql?t.map.get(e):un(t.map,e)}function Gt(e){var t=this.__data__;return Fo(e)?Wt("string"==typeof e?t.string:t.hash,e):ql?t.map.has(e):sn(t.map,e)}function $t(e,t){var n=this.__data__;return Fo(e)?Ht("string"==typeof e?n.string:n.hash,e,t):ql?n.map.set(e,t):cn(n.map,e,t),this}function Xt(e){var t=-1,n=e?e.length:0;for(this.__data__=new Kt;++t<n;)this.push(e[t])}function Qt(e,t){var n=e.__data__;if(Fo(t)){var r=n.__data__,o="string"==typeof t?r.string:r.hash;return o[t]===ae}return n.has(t)}function Zt(e){var t=this.__data__;if(Fo(e)){var n=t.__data__,r="string"==typeof e?n.string:n.hash;r[e]=ae}else t.set(e,ae)}function Jt(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function en(){this.__data__={array:[],map:null}}function tn(e){var t=this.__data__,n=t.array;return n?an(n,e):t.map["delete"](e)}function nn(e){var t=this.__data__,n=t.array;return n?un(n,e):t.map.get(e)}function rn(e){var t=this.__data__,n=t.array;return n?sn(n,e):t.map.has(e)}function on(e,t){var n=this.__data__,r=n.array;r&&(r.length<re-1?cn(r,e,t):(n.array=null,n.map=new Kt(r)));var o=n.map;return o&&o.set(e,t),this}function an(e,t){var n=ln(e,t);if(0>n)return!1;var r=e.length-1;return n==r?e.pop():Ml.call(e,n,1),!0}function un(e,t){var n=ln(e,t);return 0>n?te:e[n][1]}function sn(e,t){return ln(e,t)>-1}function ln(e,t){for(var n=e.length;n--;)if(Bi(e[n][0],t))return n;return-1}function cn(e,t,n){var r=ln(e,t);0>r?e.push([t,n]):e[r][1]=n}function pn(e,t,n,r){return e===te||Bi(e,cl[n])&&!fl.call(r,n)?t:e}function dn(e,t,n){(n===te||Bi(e[t],n))&&("number"!=typeof t||n!==te||t in e)||(e[t]=n)}function fn(e,t,n){var r=e[t];fl.call(e,t)&&Bi(r,n)&&(n!==te||t in e)||(e[t]=n)}function hn(e,t,n,r){return uc(e,function(e,o,a){t(r,e,n(e),a)}),r}function vn(e,t){return e&&$r(t,zu(t),e)}function mn(e,t){for(var n=-1,r=null==e,o=t.length,a=Array(o);++n<o;)a[n]=r?te:Hu(e,t[n]);return a}function yn(e,t,n){return e===e&&(n!==te&&(e=n>=e?e:n),t!==te&&(e=e>=t?e:t)),e}function gn(e,t,n,r,o,a,i){var u;if(r&&(u=a?r(e,o,a,i):r(e)),u!==te)return u;if(!au(e))return e;var s=Qc(e);if(s){if(u=So(e),!t)return Gr(e,u)}else{var l=Do(e),p=l==Le||l==Ue;if(Zc(e))return Lr(e,t);if(l==We||l==Re||p&&!a){if(q(e))return a?e:{};if(u=Ro(p?{}:e),!t)return Xr(e,vn(u,e))}else{if(!kn[l])return a?e:{};u=Io(e,l,gn,t)}}i||(i=new Jt);var d=i.get(e);if(d)return d;if(i.set(e,u),!s)var f=n?_o(e):zu(e);return c(f||e,function(o,a){f&&(a=o,o=e[a]),fn(u,a,gn(o,t,n,r,a,e,i))}),u}function bn(e){var t=zu(e),n=t.length;return function(r){if(null==r)return!n;for(var o=n;o--;){var a=t[o],i=e[a],u=r[a];if(u===te&&!(a in Object(r))||!i(u))return!1}return!0}}function _n(e){return au(e)?Tl(e):{}}function En(e,t,n){if("function"!=typeof e)throw new sl(oe);return Dl(function(){e.apply(te,n)},t)}function Cn(e,t,n,r){var o=-1,a=h,i=!0,u=e.length,s=[],l=t.length;if(!u)return s;n&&(t=m(t,S(n))),r?(a=v,i=!1):t.length>=re&&(a=Qt,i=!1,t=new Xt(t));e:for(;++o<u;){var c=e[o],p=n?n(c):c;if(i&&p===p){for(var d=l;d--;)if(t[d]===p)continue e;s.push(c)}else a(t,p,r)||s.push(c)}return s}function Sn(e,t){var n=!0;return uc(e,function(e,r,o){return n=!!t(e,r,o)}),n}function Rn(e,t,n,r){var o=e.length;for(n=xu(n),0>n&&(n=-n>o?0:o+n),r=r===te||r>o?o:xu(r),0>r&&(r+=o),r=n>r?0:Du(r);r>n;)e[n++]=t;return e}function In(e,t){var n=[];return uc(e,function(e,r,o){t(e,r,o)&&n.push(e)}),n}function jn(e,t,n,r,o){var a=-1,i=e.length;for(n||(n=Ao),o||(o=[]);++a<i;){var u=e[a];t>0&&n(u)?t>1?jn(u,t-1,n,r,o):y(o,u):r||(o[o.length]=u)}return o}function An(e,t){return e&&lc(e,t,zu)}function Un(e,t){return e&&cc(e,t,zu)}function Fn(e,t){return f(t,function(t){return nu(e[t])})}function Wn(e,t){t=Uo(t,e)?[t]:Ar(t);for(var n=0,r=t.length;null!=e&&r>n;)e=e[t[n++]];return n&&n==r?e:te}function Hn(e,t,n){var r=t(e);return Qc(e)?r:y(r,n(e))}function Kn(e,t){return fl.call(e,t)||"object"==typeof e&&t in e&&null===To(e)}function qn(e,t){return t in Object(e)}function Gn(e,t,n){return e>=Ll(t,n)&&e<Vl(t,n)}function $n(e,t,n){for(var r=n?v:h,o=e[0].length,a=e.length,i=a,u=Array(a),s=1/0,l=[];i--;){var c=e[i];i&&t&&(c=m(c,S(t))),s=Ll(c.length,s),u[i]=!n&&(t||o>=120&&c.length>=120)?new Xt(i&&c):te}c=e[0];var p=-1,d=u[0];e:for(;++p<o&&l.length<s;){var f=c[p],y=t?t(f):f;if(!(d?Qt(d,y):r(l,y,n))){for(i=a;--i;){var g=u[i];if(!(g?Qt(g,y):r(e[i],y,n)))continue e}d&&d.push(y),l.push(f)}}return l}function Xn(e,t,n,r){return An(e,function(e,o,a){t(r,n(e),o,a)}),r}function Qn(e,t,n){Uo(t,e)||(t=Ar(t),e=Yo(e,t),t=ma(t));var r=null==e?e:e[t];return null==r?te:u(r,e,n)}function Zn(e,t,n,r,o){return e===t?!0:null==e||null==t||!au(e)&&!iu(t)?e!==e&&t!==t:Jn(e,t,Zn,n,r,o)}function Jn(e,t,n,r,o,a){var i=Qc(e),u=Qc(t),s=Ie,l=Ie;i||(s=Do(e),s=s==Re?We:s),u||(l=Do(t),l=l==Re?We:l);var c=s==We&&!q(e),p=l==We&&!q(t),d=s==l;if(d&&!c)return a||(a=new Jt),i||Eu(e)?yo(e,t,n,r,o,a):go(e,t,s,n,r,o,a);if(!(o&ge)){var f=c&&fl.call(e,"__wrapped__"),h=p&&fl.call(t,"__wrapped__");if(f||h){var v=f?e.value():e,m=h?t.value():t;return a||(a=new Jt),n(v,m,r,o,a)}}return d?(a||(a=new Jt),bo(e,t,n,r,o,a)):!1}function er(e,t,n,r){var o=n.length,a=o,i=!r;if(null==e)return!a;for(e=Object(e);o--;){var u=n[o];if(i&&u[2]?u[1]!==e[u[0]]:!(u[0]in e))return!1}for(;++o<a;){u=n[o];var s=u[0],l=e[s],c=u[1];if(i&&u[2]){if(l===te&&!(s in e))return!1}else{var p=new Jt;if(r)var d=r(l,c,s,e,t,p);if(!(d===te?Zn(c,l,r,ye|ge,p):d))return!1}}return!0}function tr(e){return"function"==typeof e?e:null==e?Vs:"object"==typeof e?Qc(e)?ir(e[0],e[1]):ar(e):qs(e)}function nr(e){return Al(Object(e))}function rr(e){e=null==e?e:Object(e);var t=[];for(var n in e)t.push(n);return t}function or(e,t){var n=-1,r=zi(e)?Array(e.length):[];return uc(e,function(e,o,a){r[++n]=t(e,o,a)}),r}function ar(e){var t=Co(e);return 1==t.length&&t[0][2]?Ko(t[0][0],t[0][1]):function(n){return n===e||er(n,e,t)}}function ir(e,t){return Uo(e)&&Ho(t)?Ko(e,t):function(n){var r=Hu(n,e);return r===te&&r===t?qu(n,e):Zn(t,r,te,ye|ge)}}function ur(e,t,n,r,o){if(e!==t){if(!Qc(t)&&!Eu(t))var a=Yu(t);c(a||t,function(i,u){if(a&&(u=i,i=t[u]),au(i))o||(o=new Jt),sr(e,t,u,n,ur,r,o);else{var s=r?r(e[u],i,u+"",e,t,o):te;s===te&&(s=i),dn(e,u,s)}})}}function sr(e,t,n,r,o,a,i){var u=e[n],s=t[n],l=i.get(s);if(l)return void dn(e,n,l);var c=a?a(u,s,n+"",e,t,i):te,p=c===te;p&&(c=s,Qc(s)||Eu(s)?Qc(u)?c=u:Yi(u)?c=Gr(u):(p=!1,c=gn(s,!0)):vu(s)||Ki(s)?Ki(u)?c=ku(u):!au(u)||r&&nu(u)?(p=!1,c=gn(s,!0)):c=u:p=!1),i.set(s,c),p&&o(c,s,r,a,i),i["delete"](s),dn(e,n,c)}function lr(e,t){var n=e.length;if(n)return t+=0>t?n:0,z(t,n)?e[t]:te}function cr(e,t,n){var r=-1;t=m(t.length?t:[Vs],S(Oo()));var o=or(e,function(e,n,o){var a=m(t,function(t){return t(e)});return{criteria:a,index:++r,value:e}});return x(o,function(e,t){return L(e,t,n)})}function pr(e,t){return e=Object(e),g(t,function(t,n){return n in e&&(t[n]=e[n]),t},{})}function dr(e,t){for(var n=-1,r=Eo(e),o=r.length,a={};++n<o;){var i=r[n],u=e[i];t(u,i)&&(a[i]=u)}return a}function fr(e){return function(t){return null==t?te:t[e]}}function hr(e){return function(t){return Wn(t,e)}}function vr(e,t,n,r){var o=r?P:C,a=-1,i=t.length,u=e;for(n&&(u=m(e,S(n)));++a<i;)for(var s=0,l=t[a],c=n?n(l):l;(s=o(u,c,s,r))>-1;)u!==e&&Ml.call(u,s,1),Ml.call(e,s,1);return e}function mr(e,t){for(var n=e?t.length:0,r=n-1;n--;){var o=t[n];if(r==n||o!=a){var a=o;if(z(o))Ml.call(e,o,1);else if(Uo(o,e))delete e[o];else{var i=Ar(o),u=Yo(e,i);null!=u&&delete u[ma(i)]}}}return e}function yr(e,t){return e+Sl(Fl()*(t-e+1))}function gr(e,t,n,r){for(var o=-1,a=Vl(kl((t-e)/(n||1)),0),i=Array(a);a--;)i[r?a:++o]=e,e+=n;return i}function br(e,t){var n="";if(!e||1>t||t>Te)return n;do t%2&&(n+=e),t=Sl(t/2),t&&(e+=e);while(t);return n}function _r(e,t,n,r){t=Uo(t,e)?[t]:Ar(t);for(var o=-1,a=t.length,i=a-1,u=e;null!=u&&++o<a;){var s=t[o];if(au(u)){var l=n;if(o!=i){var c=u[s];l=r?r(c,s,u):te,l===te&&(l=null==c?z(t[o+1])?[]:{}:c)}fn(u,s,l)}u=u[s]}return e}function Er(e,t,n){var r=-1,o=e.length;0>t&&(t=-t>o?0:o+t),n=n>o?o:n,0>n&&(n+=o),o=t>n?0:n-t>>>0,t>>>=0;for(var a=Array(o);++r<o;)a[r]=e[r+t];return a}function Nr(e,t){var n;return uc(e,function(e,r,o){return n=t(e,r,o),!n}),!!n}function Or(e,t,n){var r=0,o=e?e.length:r;if("number"==typeof t&&t===t&&Se>=o){for(;o>r;){var a=r+o>>>1,i=e[a];(n?t>=i:t>i)&&null!==i?r=a+1:o=a}return o}return Cr(e,t,Vs,n)}function Cr(e,t,n,r){t=n(t);for(var o=0,a=e?e.length:0,i=t!==t,u=null===t,s=t===te;a>o;){var l=Sl((o+a)/2),c=n(e[l]),p=c!==te,d=c===c;if(i)var f=d||r;else f=u?d&&p&&(r||null!=c):s?d&&(r||p):null==c?!1:r?t>=c:t>c;f?o=l+1:a=l}return Ll(a,ke)}function Pr(e){return wr(e)}function wr(e,t){for(var n=0,r=e.length,o=e[0],a=t?t(o):o,i=a,u=1,s=[o];++n<r;)o=e[n],a=t?t(o):o,Bi(a,i)||(i=a,s[u++]=o);return s}function Tr(e,t,n){var r=-1,o=h,a=e.length,i=!0,u=[],s=u;if(n)i=!1,o=v;else if(a>=re){var l=t?null:dc(e);if(l)return X(l);i=!1,o=Qt,s=new Xt}else s=t?[]:u;e:for(;++r<a;){var c=e[r],p=t?t(c):c;if(i&&p===p){for(var d=s.length;d--;)if(s[d]===p)continue e;t&&s.push(p),u.push(c)}else o(s,p,n)||(s!==u&&s.push(p),u.push(c))}return u}function xr(e,t){t=Uo(t,e)?[t]:Ar(t),e=Yo(e,t);var n=ma(t);return null!=e&&Ku(e,n)?delete e[n]:!0}function Dr(e,t,n,r){return _r(e,t,n(Wn(e,t)),r)}function Mr(e,t,n,r){for(var o=e.length,a=r?o:-1;(r?a--:++a<o)&&t(e[a],a,e););return n?Er(e,r?0:a,r?a+1:o):Er(e,r?a+1:0,r?o:a)}function kr(e,t){var n=e;return n instanceof o&&(n=n.value()),g(t,function(e,t){return t.func.apply(t.thisArg,y([e],t.args))},n)}function Sr(e,t,n){for(var r=-1,o=e.length;++r<o;)var a=a?y(Cn(a,e[r],t,n),Cn(e[r],a,t,n)):e[r];return a&&a.length?Tr(a,t,n):[]}function Rr(e,t,n){for(var r=-1,o=e.length,a=t.length,i={};++r<o;){var u=a>r?t[r]:te;n(i,e[r],u)}return i}function Ir(e){return Yi(e)?e:[]}function jr(e){return"function"==typeof e?e:Vs}function Ar(e){return Qc(e)?e:yc(e)}function Vr(e,t,n){var r=e.length;return n=n===te?r:n,!t&&n>=r?e:Er(e,t,n)}function Lr(e,t){if(t)return e.slice();var n=new e.constructor(e.length);return e.copy(n),n}function Ur(e){var t=new e.constructor(e.byteLength); return new Nl(t).set(new Nl(e)),t}function Fr(e,t){var n=t?Ur(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}function Br(e,t,n){var r=t?n(G(e),!0):G(e);return g(r,a,new e.constructor)}function Wr(e){var t=new e.constructor(e.source,xt.exec(e));return t.lastIndex=e.lastIndex,t}function Hr(e,t,n){var r=t?n(X(e),!0):X(e);return g(r,i,new e.constructor)}function Kr(e){return ac?Object(ac.call(e)):{}}function qr(e,t){var n=t?Ur(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.length)}function zr(e,t,n,r){for(var o=-1,a=e.length,i=n.length,u=-1,s=t.length,l=Vl(a-i,0),c=Array(s+l),p=!r;++u<s;)c[u]=t[u];for(;++o<i;)(p||a>o)&&(c[n[o]]=e[o]);for(;l--;)c[u++]=e[o++];return c}function Yr(e,t,n,r){for(var o=-1,a=e.length,i=-1,u=n.length,s=-1,l=t.length,c=Vl(a-u,0),p=Array(c+l),d=!r;++o<c;)p[o]=e[o];for(var f=o;++s<l;)p[f+s]=t[s];for(;++i<u;)(d||a>o)&&(p[f+n[i]]=e[o++]);return p}function Gr(e,t){var n=-1,r=e.length;for(t||(t=Array(r));++n<r;)t[n]=e[n];return t}function $r(e,t,n,r){n||(n={});for(var o=-1,a=t.length;++o<a;){var i=t[o],u=r?r(n[i],e[i],i,n,e):e[i];fn(n,i,u)}return n}function Xr(e,t){return $r(e,xo(e),t)}function Qr(e,t){return function(n,r){var o=Qc(n)?s:hn,a=t?t():{};return o(n,e,Oo(r),a)}}function Zr(e){return ki(function(t,n){var r=-1,o=n.length,a=o>1?n[o-1]:te,i=o>2?n[2]:te;for(a="function"==typeof a?(o--,a):te,i&&Lo(n[0],n[1],i)&&(a=3>o?te:a,o=1),t=Object(t);++r<o;){var u=n[r];u&&e(t,u,r,a)}return t})}function Jr(e,t){return function(n,r){if(null==n)return n;if(!zi(n))return e(n,r);for(var o=n.length,a=t?o:-1,i=Object(n);(t?a--:++a<o)&&r(i[a],a,i)!==!1;);return n}}function eo(e){return function(t,n,r){for(var o=-1,a=Object(t),i=r(t),u=i.length;u--;){var s=i[e?u:++o];if(n(a[s],s,a)===!1)break}return t}}function to(e,t,n){function r(){var t=this&&this!==zn&&this instanceof r?a:e;return t.apply(o?n:this,arguments)}var o=t&ue,a=oo(e);return r}function no(e){return function(t){t=Ru(t);var n=wn.test(t)?Z(t):te,r=n?n[0]:t.charAt(0),o=n?Vr(n,1).join(""):t.slice(1);return r[e]()+o}}function ro(e){return function(t){return g(Rs(fs(t).replace(Nn,"")),e,"")}}function oo(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=_n(e.prototype),r=e.apply(n,t);return au(r)?r:n}}function ao(e,t,n){function r(){for(var a=arguments.length,i=Array(a),s=a,l=wo(r);s--;)i[s]=arguments[s];var c=3>a&&i[0]!==l&&i[a-1]!==l?[]:$(i,l);if(a-=c.length,n>a)return ho(e,t,uo,r.placeholder,te,i,c,te,te,n-a);var p=this&&this!==zn&&this instanceof r?o:e;return u(p,this,i)}var o=oo(e);return r}function io(e){return ki(function(t){t=jn(t,1);var n=t.length,o=n,a=r.prototype.thru;for(e&&t.reverse();o--;){var i=t[o];if("function"!=typeof i)throw new sl(oe);if(a&&!u&&"wrapper"==No(i))var u=new r([],!0)}for(o=u?o:n;++o<n;){i=t[o];var s=No(i),l="wrapper"==s?fc(i):te;u=l&&Bo(l[0])&&l[1]==(he|ce|de|ve)&&!l[4].length&&1==l[9]?u[No(l[0])].apply(u,l[3]):1==i.length&&Bo(i)?u[s]():u.thru(i)}return function(){var e=arguments,r=e[0];if(u&&1==e.length&&Qc(r)&&r.length>=re)return u.plant(r).value();for(var o=0,a=n?t[o].apply(this,e):r;++o<n;)a=t[o].call(this,a);return a}})}function uo(e,t,n,r,o,a,i,u,s,l){function c(){for(var y=arguments.length,g=y,b=Array(y);g--;)b[g]=arguments[g];if(h)var _=wo(c),E=U(b,_);if(r&&(b=zr(b,r,o,h)),a&&(b=Yr(b,a,i,h)),y-=E,h&&l>y){var N=$(b,_);return ho(e,t,uo,c.placeholder,n,b,N,u,s,l-y)}var O=d?n:this,C=f?O[e]:e;return y=b.length,u?b=Go(b,u):v&&y>1&&b.reverse(),p&&y>s&&(b.length=s),this&&this!==zn&&this instanceof c&&(C=m||oo(C)),C.apply(O,b)}var p=t&he,d=t&ue,f=t&se,h=t&(ce|pe),v=t&me,m=f?te:oo(e);return c}function so(e,t){return function(n,r){return Xn(n,e,t(r),{})}}function lo(e){return ki(function(t){return t=1==t.length&&Qc(t[0])?m(t[0],S(Oo())):m(jn(t,1,Vo),S(Oo())),ki(function(n){var r=this;return e(t,function(e){return u(e,r,n)})})})}function co(e,t){t=t===te?" ":t+"";var n=t.length;if(2>n)return n?br(t,e):t;var r=br(t,kl(e/Q(t)));return wn.test(t)?Vr(Z(r),0,e).join(""):r.slice(0,e)}function po(e,t,n,r){function o(){for(var t=-1,s=arguments.length,l=-1,c=r.length,p=Array(c+s),d=this&&this!==zn&&this instanceof o?i:e;++l<c;)p[l]=r[l];for(;s--;)p[l++]=arguments[++t];return u(d,a?n:this,p)}var a=t&ue,i=oo(e);return o}function fo(e){return function(t,n,r){return r&&"number"!=typeof r&&Lo(t,n,r)&&(n=r=te),t=Mu(t),t=t===t?t:0,n===te?(n=t,t=0):n=Mu(n)||0,r=r===te?n>t?1:-1:Mu(r)||0,gr(t,n,r,e)}}function ho(e,t,n,r,o,a,i,u,s,l){var c=t&ce,p=c?i:te,d=c?te:i,f=c?a:te,h=c?te:a;t|=c?de:fe,t&=~(c?fe:de),t&le||(t&=~(ue|se));var v=[e,t,o,f,p,h,d,u,s,l],m=n.apply(te,v);return Bo(e)&&mc(m,v),m.placeholder=r,m}function vo(e){var t=il[e];return function(e,n){if(e=Mu(e),n=xu(n)){var r=(Ru(e)+"e").split("e"),o=t(r[0]+"e"+(+r[1]+n));return r=(Ru(o)+"e").split("e"),+(r[0]+"e"+(+r[1]-n))}return t(e)}}function mo(e,t,n,r,o,a,i,u){var s=t&se;if(!s&&"function"!=typeof e)throw new sl(oe);var l=r?r.length:0;if(l||(t&=~(de|fe),r=o=te),i=i===te?i:Vl(xu(i),0),u=u===te?u:xu(u),l-=o?o.length:0,t&fe){var c=r,p=o;r=o=te}var d=s?te:fc(e),f=[e,t,n,r,o,c,p,a,i,u];if(d&&qo(f,d),e=f[0],t=f[1],n=f[2],r=f[3],o=f[4],u=f[9]=null==f[9]?s?0:e.length:Vl(f[9]-l,0),!u&&t&(ce|pe)&&(t&=~(ce|pe)),t&&t!=ue)h=t==ce||t==pe?ao(e,t,u):t!=de&&t!=(ue|de)||o.length?uo.apply(te,f):po(e,t,n,r);else var h=to(e,t,n);var v=d?pc:mc;return v(h,f)}function yo(e,t,n,r,o,a){var i=-1,u=o&ge,s=o&ye,l=e.length,c=t.length;if(l!=c&&!(u&&c>l))return!1;var p=a.get(e);if(p)return p==t;var d=!0;for(a.set(e,t);++i<l;){var f=e[i],h=t[i];if(r)var v=u?r(h,f,i,t,e,a):r(f,h,i,e,t,a);if(v!==te){if(v)continue;d=!1;break}if(s){if(!_(t,function(e){return f===e||n(f,e,r,o,a)})){d=!1;break}}else if(f!==h&&!n(f,h,r,o,a)){d=!1;break}}return a["delete"](e),d}function go(e,t,n,r,o,a,i){switch(n){case Qe:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case Xe:return!(e.byteLength!=t.byteLength||!r(new Nl(e),new Nl(t)));case je:case Ae:return+e==+t;case Ve:return e.name==t.name&&e.message==t.message;case Be:return e!=+e?t!=+t:e==+t;case Ke:case ze:return e==t+"";case Fe:var u=G;case qe:var s=a&ge;if(u||(u=X),e.size!=t.size&&!s)return!1;var l=i.get(e);return l?l==t:(a|=ye,i.set(e,t),yo(u(e),u(t),r,o,a,i));case Ye:if(ac)return ac.call(e)==ac.call(t)}return!1}function bo(e,t,n,r,o,a){var i=o&ge,u=zu(e),s=u.length,l=zu(t),c=l.length;if(s!=c&&!i)return!1;for(var p=s;p--;){var d=u[p];if(!(i?d in t:Kn(t,d)))return!1}var f=a.get(e);if(f)return f==t;var h=!0;a.set(e,t);for(var v=i;++p<s;){d=u[p];var m=e[d],y=t[d];if(r)var g=i?r(y,m,d,t,e,a):r(m,y,d,e,t,a);if(!(g===te?m===y||n(m,y,r,o,a):g)){h=!1;break}v||(v="constructor"==d)}if(h&&!v){var b=e.constructor,_=t.constructor;b!=_&&"constructor"in e&&"constructor"in t&&!("function"==typeof b&&b instanceof b&&"function"==typeof _&&_ instanceof _)&&(h=!1)}return a["delete"](e),h}function _o(e){return Hn(e,zu,xo)}function Eo(e){return Hn(e,Yu,vc)}function No(e){for(var t=e.name+"",n=Zl[t],r=fl.call(Zl,t)?n.length:0;r--;){var o=n[r],a=o.func;if(null==a||a==e)return o.name}return t}function Oo(){var e=t.iteratee||Ls;return e=e===Ls?tr:e,arguments.length?e(arguments[0],arguments[1]):e}function Co(e){for(var t=ts(e),n=t.length;n--;)t[n][2]=Ho(t[n][1]);return t}function Po(e,t){var n=e[t];return pu(n)?n:te}function wo(e){var n=fl.call(t,"placeholder")?t:e;return n.placeholder}function To(e){return Rl(Object(e))}function xo(e){return Pl(Object(e))}function Do(e){return ml.call(e)}function Mo(e,t,n){for(var r=-1,o=n.length;++r<o;){var a=n[r],i=a.size;switch(a.type){case"drop":e+=i;break;case"dropRight":t-=i;break;case"take":t=Ll(t,e+i);break;case"takeRight":e=Vl(e,t-i)}}return{start:e,end:t}}function ko(e,t,n){t=Uo(t,e)?[t]:Ar(t);for(var r,o=-1,a=t.length;++o<a;){var i=t[o];if(!(r=null!=e&&n(e,i)))break;e=e[i]}if(r)return r;var a=e?e.length:0;return!!a&&ou(a)&&z(i,a)&&(Qc(e)||bu(e)||Ki(e))}function So(e){var t=e.length,n=e.constructor(t);return t&&"string"==typeof e[0]&&fl.call(e,"index")&&(n.index=e.index,n.input=e.input),n}function Ro(e){return"function"!=typeof e.constructor||Wo(e)?{}:_n(To(e))}function Io(e,t,n,r){var o=e.constructor;switch(t){case Xe:return Ur(e);case je:case Ae:return new o(+e);case Qe:return Fr(e,r);case Ze:case Je:case et:case tt:case nt:case rt:case ot:case at:case it:return qr(e,r);case Fe:return Br(e,r,n);case Be:case ze:return new o(e);case Ke:return Wr(e);case qe:return Hr(e,r,n);case Ye:return Kr(e)}}function jo(e){var t=e?e.length:te;return ou(t)&&(Qc(e)||bu(e)||Ki(e))?M(t,String):null}function Ao(e){return Yi(e)&&(Qc(e)||Ki(e))}function Vo(e){return Qc(e)&&!(2==e.length&&!nu(e[0]))}function Lo(e,t,n){if(!au(n))return!1;var r=typeof t;return("number"==r?zi(n)&&z(t,n.length):"string"==r&&t in n)?Bi(n[t],e):!1}function Uo(e,t){var n=typeof e;return"number"==n||"symbol"==n?!0:!Qc(e)&&(_u(e)||gt.test(e)||!yt.test(e)||null!=t&&e in Object(t))}function Fo(e){var t=typeof e;return"number"==t||"boolean"==t||"string"==t&&"__proto__"!=e||null==e}function Bo(e){var n=No(e),r=t[n];if("function"!=typeof r||!(n in o.prototype))return!1;if(e===r)return!0;var a=fc(r);return!!a&&e===a[0]}function Wo(e){var t=e&&e.constructor,n="function"==typeof t&&t.prototype||cl;return e===n}function Ho(e){return e===e&&!au(e)}function Ko(e,t){return function(n){return null==n?!1:n[e]===t&&(t!==te||e in Object(n))}}function qo(e,t){var n=e[1],r=t[1],o=n|r,a=(ue|se|he)>o,i=r==he&&n==ce||r==he&&n==ve&&e[7].length<=t[8]||r==(he|ve)&&t[7].length<=t[8]&&n==ce;if(!a&&!i)return e;r&ue&&(e[2]=t[2],o|=n&ue?0:le);var u=t[3];if(u){var s=e[3];e[3]=s?zr(s,u,t[4]):u,e[4]=s?$(e[3],ie):t[4]}return u=t[5],u&&(s=e[5],e[5]=s?Yr(s,u,t[6]):u,e[6]=s?$(e[5],ie):t[6]),u=t[7],u&&(e[7]=u),r&he&&(e[8]=null==e[8]?t[8]:Ll(e[8],t[8])),null==e[9]&&(e[9]=t[9]),e[0]=t[0],e[1]=o,e}function zo(e,t,n,r,o,a){return au(e)&&au(t)&&ur(e,t,te,zo,a.set(t,e)),e}function Yo(e,t){return 1==t.length?e:Wn(e,Er(t,0,-1))}function Go(e,t){for(var n=e.length,r=Ll(t.length,n),o=Gr(e);r--;){var a=t[r];e[r]=z(a,n)?o[a]:te}return e}function $o(e){return"string"==typeof e||_u(e)?e:e+""}function Xo(e){if(null!=e){try{return dl.call(e)}catch(t){}try{return e+""}catch(t){}}return""}function Qo(e){if(e instanceof o)return e.clone();var t=new r(e.__wrapped__,e.__chain__);return t.__actions__=Gr(e.__actions__),t.__index__=e.__index__,t.__values__=e.__values__,t}function Zo(e,t,n){t=(n?Lo(e,t,n):t===te)?1:Vl(xu(t),0);var r=e?e.length:0;if(!r||1>t)return[];for(var o=0,a=0,i=Array(kl(r/t));r>o;)i[a++]=Er(e,o,o+=t);return i}function Jo(e){for(var t=-1,n=e?e.length:0,r=0,o=[];++t<n;){var a=e[t];a&&(o[r++]=a)}return o}function ea(){var e=arguments.length,t=Ai(arguments[0]);if(2>e)return e?Gr(t):[];for(var n=Array(e-1);e--;)n[e-1]=arguments[e];return l(t,jn(n,1))}function ta(e,t,n){var r=e?e.length:0;return r?(t=n||t===te?1:xu(t),Er(e,0>t?0:t,r)):[]}function na(e,t,n){var r=e?e.length:0;return r?(t=n||t===te?1:xu(t),t=r-t,Er(e,0,0>t?0:t)):[]}function ra(e,t){return e&&e.length?Mr(e,Oo(t,3),!0,!0):[]}function oa(e,t){return e&&e.length?Mr(e,Oo(t,3),!0):[]}function aa(e,t,n,r){var o=e?e.length:0;return o?(n&&"number"!=typeof n&&Lo(e,t,n)&&(n=0,r=o),Rn(e,t,n,r)):[]}function ia(e,t){return e&&e.length?O(e,Oo(t,3)):-1}function ua(e,t){return e&&e.length?O(e,Oo(t,3),!0):-1}function sa(e){var t=e?e.length:0;return t?jn(e,1):[]}function la(e){var t=e?e.length:0;return t?jn(e,we):[]}function ca(e,t){var n=e?e.length:0;return n?(t=t===te?1:xu(t),jn(e,t)):[]}function pa(e){for(var t=-1,n=e?e.length:0,r={};++t<n;){var o=e[t];r[o[0]]=o[1]}return r}function da(e){return e&&e.length?e[0]:te}function fa(e,t,n){var r=e?e.length:0;return r?(n=xu(n),0>n&&(n=Vl(r+n,0)),C(e,t,n)):-1}function ha(e){return na(e,1)}function va(e,t){return e?jl.call(e,t):""}function ma(e){var t=e?e.length:0;return t?e[t-1]:te}function ya(e,t,n){var r=e?e.length:0;if(!r)return-1;var o=r;if(n!==te&&(o=xu(n),o=(0>o?Vl(r+o,0):Ll(o,r-1))+1),t!==t)return K(e,o,!0);for(;o--;)if(e[o]===t)return o;return-1}function ga(e,t){return e&&e.length?lr(e,xu(t)):te}function ba(e,t){return e&&e.length&&t&&t.length?vr(e,t):e}function _a(e,t,n){return e&&e.length&&t&&t.length?vr(e,t,Oo(n)):e}function Ea(e,t,n){return e&&e.length&&t&&t.length?vr(e,t,te,n):e}function Na(e,t){var n=[];if(!e||!e.length)return n;var r=-1,o=[],a=e.length;for(t=Oo(t,3);++r<a;){var i=e[r];t(i,r,e)&&(n.push(i),o.push(r))}return mr(e,o),n}function Oa(e){return e?Wl.call(e):e}function Ca(e,t,n){var r=e?e.length:0;return r?(n&&"number"!=typeof n&&Lo(e,t,n)?(t=0,n=r):(t=null==t?0:xu(t),n=n===te?r:xu(n)),Er(e,t,n)):[]}function Pa(e,t){return Or(e,t)}function wa(e,t,n){return Cr(e,t,Oo(n))}function Ta(e,t){var n=e?e.length:0;if(n){var r=Or(e,t);if(n>r&&Bi(e[r],t))return r}return-1}function xa(e,t){return Or(e,t,!0)}function Da(e,t,n){return Cr(e,t,Oo(n),!0)}function Ma(e,t){var n=e?e.length:0;if(n){var r=Or(e,t,!0)-1;if(Bi(e[r],t))return r}return-1}function ka(e){return e&&e.length?Pr(e):[]}function Sa(e,t){return e&&e.length?wr(e,Oo(t)):[]}function Ra(e){return ta(e,1)}function Ia(e,t,n){return e&&e.length?(t=n||t===te?1:xu(t),Er(e,0,0>t?0:t)):[]}function ja(e,t,n){var r=e?e.length:0;return r?(t=n||t===te?1:xu(t),t=r-t,Er(e,0>t?0:t,r)):[]}function Aa(e,t){return e&&e.length?Mr(e,Oo(t,3),!1,!0):[]}function Va(e,t){return e&&e.length?Mr(e,Oo(t,3)):[]}function La(e){return e&&e.length?Tr(e):[]}function Ua(e,t){return e&&e.length?Tr(e,Oo(t)):[]}function Fa(e,t){return e&&e.length?Tr(e,te,t):[]}function Ba(e){if(!e||!e.length)return[];var t=0;return e=f(e,function(e){return Yi(e)?(t=Vl(e.length,t),!0):void 0}),M(t,function(t){return m(e,fr(t))})}function Wa(e,t){if(!e||!e.length)return[];var n=Ba(e);return null==t?n:m(n,function(e){return u(t,te,e)})}function Ha(e,t){return Rr(e||[],t||[],fn)}function Ka(e,t){return Rr(e||[],t||[],_r)}function qa(e){var n=t(e);return n.__chain__=!0,n}function za(e,t){return t(e),e}function Ya(e,t){return t(e)}function Ga(){return qa(this)}function $a(){return new r(this.value(),this.__chain__)}function Xa(){this.__values__===te&&(this.__values__=Tu(this.value()));var e=this.__index__>=this.__values__.length,t=e?te:this.__values__[this.__index__++];return{done:e,value:t}}function Qa(){return this}function Za(e){for(var t,r=this;r instanceof n;){var o=Qo(r);o.__index__=0,o.__values__=te,t?a.__wrapped__=o:t=o;var a=o;r=r.__wrapped__}return a.__wrapped__=e,t}function Ja(){var e=this.__wrapped__;if(e instanceof o){var t=e;return this.__actions__.length&&(t=new o(this)),t=t.reverse(),t.__actions__.push({func:Ya,args:[Oa],thisArg:te}),new r(t,this.__chain__)}return this.thru(Oa)}function ei(){return kr(this.__wrapped__,this.__actions__)}function ti(e,t,n){var r=Qc(e)?d:Sn;return n&&Lo(e,t,n)&&(t=te),r(e,Oo(t,3))}function ni(e,t){var n=Qc(e)?f:In;return n(e,Oo(t,3))}function ri(e,t){if(t=Oo(t,3),Qc(e)){var n=O(e,t);return n>-1?e[n]:te}return N(e,t,uc)}function oi(e,t){if(t=Oo(t,3),Qc(e)){var n=O(e,t,!0);return n>-1?e[n]:te}return N(e,t,sc)}function ai(e,t){return jn(pi(e,t),1)}function ii(e,t){return jn(pi(e,t),we)}function ui(e,t,n){return n=n===te?1:xu(n),jn(pi(e,t),n)}function si(e,t){return"function"==typeof t&&Qc(e)?c(e,t):uc(e,Oo(t))}function li(e,t){return"function"==typeof t&&Qc(e)?p(e,t):sc(e,Oo(t))}function ci(e,t,n,r){e=zi(e)?e:us(e),n=n&&!r?xu(n):0;var o=e.length;return 0>n&&(n=Vl(o+n,0)),bu(e)?o>=n&&e.indexOf(t,n)>-1:!!o&&C(e,t,n)>-1}function pi(e,t){var n=Qc(e)?m:or;return n(e,Oo(t,3))}function di(e,t,n,r){return null==e?[]:(Qc(t)||(t=null==t?[]:[t]),n=r?te:n,Qc(n)||(n=null==n?[]:[n]),cr(e,t,n))}function fi(e,t,n){var r=Qc(e)?g:T,o=arguments.length<3;return r(e,Oo(t,4),n,o,uc)}function hi(e,t,n){var r=Qc(e)?b:T,o=arguments.length<3;return r(e,Oo(t,4),n,o,sc)}function vi(e,t){var n=Qc(e)?f:In;return t=Oo(t,3),n(e,function(e,n,r){return!t(e,n,r)})}function mi(e){var t=zi(e)?e:us(e),n=t.length;return n>0?t[yr(0,n-1)]:te}function yi(e,t,n){var r=-1,o=Tu(e),a=o.length,i=a-1;for(t=(n?Lo(e,t,n):t===te)?1:yn(xu(t),0,a);++r<t;){var u=yr(r,i),s=o[u];o[u]=o[r],o[r]=s}return o.length=t,o}function gi(e){return yi(e,Me)}function bi(e){if(null==e)return 0;if(zi(e)){var t=e.length;return t&&bu(e)?Q(e):t}if(iu(e)){var n=Do(e);if(n==Fe||n==qe)return e.size}return zu(e).length}function _i(e,t,n){var r=Qc(e)?_:Nr;return n&&Lo(e,t,n)&&(t=te),r(e,Oo(t,3))}function Ei(e,t){if("function"!=typeof t)throw new sl(oe);return e=xu(e),function(){return--e<1?t.apply(this,arguments):void 0}}function Ni(e,t,n){return t=n?te:t,t=e&&null==t?e.length:t,mo(e,he,te,te,te,te,t)}function Oi(e,t){var n;if("function"!=typeof t)throw new sl(oe);return e=xu(e),function(){return--e>0&&(n=t.apply(this,arguments)),1>=e&&(t=te),n}}function Ci(e,t,n){t=n?te:t;var r=mo(e,ce,te,te,te,te,te,t);return r.placeholder=Ci.placeholder,r}function Pi(e,t,n){t=n?te:t;var r=mo(e,pe,te,te,te,te,te,t);return r.placeholder=Pi.placeholder,r}function wi(e,t,n){function r(t){var n=d,r=f;return d=f=te,g=t,v=e.apply(r,n)}function o(e){return g=e,m=Dl(u,t),b?r(e):v}function a(e){var n=e-y,r=e-g,o=t-n;return _?Ll(o,h-r):o}function i(e){var n=e-y,r=e-g;return!y||n>=t||0>n||_&&r>=h}function u(){var e=Wc();return i(e)?s(e):void(m=Dl(u,a(e)))}function s(e){return Ol(m),m=te,E&&d?r(e):(d=f=te,v)}function l(){m!==te&&Ol(m),y=g=0,d=f=m=te}function c(){return m===te?v:s(Wc())}function p(){var e=Wc(),n=i(e);if(d=arguments,f=this,y=e,n){if(m===te)return o(y);if(_)return Ol(m),m=Dl(u,t),r(y)}return m===te&&(m=Dl(u,t)),v}var d,f,h,v,m,y=0,g=0,b=!1,_=!1,E=!0;if("function"!=typeof e)throw new sl(oe);return t=Mu(t)||0,au(n)&&(b=!!n.leading,_="maxWait"in n,h=_?Vl(Mu(n.maxWait)||0,t):h,E="trailing"in n?!!n.trailing:E),p.cancel=l,p.flush=c,p}function Ti(e){return mo(e,me)}function xi(e,t){if("function"!=typeof e||t&&"function"!=typeof t)throw new sl(oe);var n=function(){var r=arguments,o=t?t.apply(this,r):r[0],a=n.cache;if(a.has(o))return a.get(o);var i=e.apply(this,r);return n.cache=a.set(o,i),i};return n.cache=new(xi.Cache||Kt),n}function Di(e){if("function"!=typeof e)throw new sl(oe);return function(){return!e.apply(this,arguments)}}function Mi(e){return Oi(2,e)}function ki(e,t){if("function"!=typeof e)throw new sl(oe);return t=Vl(t===te?e.length-1:xu(t),0),function(){for(var n=arguments,r=-1,o=Vl(n.length-t,0),a=Array(o);++r<o;)a[r]=n[t+r];switch(t){case 0:return e.call(this,a);case 1:return e.call(this,n[0],a);case 2:return e.call(this,n[0],n[1],a)}var i=Array(t+1);for(r=-1;++r<t;)i[r]=n[r];return i[t]=a,u(e,this,i)}}function Si(e,t){if("function"!=typeof e)throw new sl(oe);return t=t===te?0:Vl(xu(t),0),ki(function(n){var r=n[t],o=Vr(n,0,t);return r&&y(o,r),u(e,this,o)})}function Ri(e,t,n){var r=!0,o=!0;if("function"!=typeof e)throw new sl(oe);return au(n)&&(r="leading"in n?!!n.leading:r,o="trailing"in n?!!n.trailing:o),wi(e,t,{leading:r,maxWait:t,trailing:o})}function Ii(e){return Ni(e,1)}function ji(e,t){return t=null==t?Vs:t,Gc(t,e)}function Ai(){if(!arguments.length)return[];var e=arguments[0];return Qc(e)?e:[e]}function Vi(e){return gn(e,!1,!0)}function Li(e,t){return gn(e,!1,!0,t)}function Ui(e){return gn(e,!0,!0)}function Fi(e,t){return gn(e,!0,!0,t)}function Bi(e,t){return e===t||e!==e&&t!==t}function Wi(e,t){return e>t}function Hi(e,t){return e>=t}function Ki(e){return Yi(e)&&fl.call(e,"callee")&&(!xl.call(e,"callee")||ml.call(e)==Re)}function qi(e){return iu(e)&&ml.call(e)==Xe}function zi(e){return null!=e&&ou(hc(e))&&!nu(e)}function Yi(e){return iu(e)&&zi(e)}function Gi(e){return e===!0||e===!1||iu(e)&&ml.call(e)==je}function $i(e){return iu(e)&&ml.call(e)==Ae}function Xi(e){return!!e&&1===e.nodeType&&iu(e)&&!vu(e)}function Qi(e){if(zi(e)&&(Qc(e)||bu(e)||nu(e.splice)||Ki(e)||Zc(e)))return!e.length;if(iu(e)){var t=Do(e);if(t==Fe||t==qe)return!e.size}for(var n in e)if(fl.call(e,n))return!1;return!(Ql&&zu(e).length)}function Zi(e,t){return Zn(e,t)}function Ji(e,t,n){n="function"==typeof n?n:te;var r=n?n(e,t):te;return r===te?Zn(e,t,n):!!r}function eu(e){return iu(e)?ml.call(e)==Ve||"string"==typeof e.message&&"string"==typeof e.name:!1}function tu(e){return"number"==typeof e&&Il(e)}function nu(e){var t=au(e)?ml.call(e):"";return t==Le||t==Ue}function ru(e){return"number"==typeof e&&e==xu(e)}function ou(e){return"number"==typeof e&&e>-1&&e%1==0&&Te>=e}function au(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function iu(e){return!!e&&"object"==typeof e}function uu(e){return iu(e)&&Do(e)==Fe}function su(e,t){return e===t||er(e,t,Co(t))}function lu(e,t,n){return n="function"==typeof n?n:te,er(e,t,Co(t),n)}function cu(e){return hu(e)&&e!=+e}function pu(e){if(!au(e))return!1;var t=nu(e)||q(e)?gl:St;return t.test(Xo(e))}function du(e){return null===e}function fu(e){return null==e}function hu(e){return"number"==typeof e||iu(e)&&ml.call(e)==Be}function vu(e){if(!iu(e)||ml.call(e)!=We||q(e))return!1;var t=To(e);if(null===t)return!0;var n=fl.call(t,"constructor")&&t.constructor;return"function"==typeof n&&n instanceof n&&dl.call(n)==vl}function mu(e){return au(e)&&ml.call(e)==Ke}function yu(e){return ru(e)&&e>=-Te&&Te>=e}function gu(e){return iu(e)&&Do(e)==qe}function bu(e){return"string"==typeof e||!Qc(e)&&iu(e)&&ml.call(e)==ze}function _u(e){return"symbol"==typeof e||iu(e)&&ml.call(e)==Ye}function Eu(e){return iu(e)&&ou(e.length)&&!!Mn[ml.call(e)]}function Nu(e){return e===te}function Ou(e){return iu(e)&&Do(e)==Ge}function Cu(e){return iu(e)&&ml.call(e)==$e}function Pu(e,t){return t>e}function wu(e,t){return t>=e}function Tu(e){if(!e)return[];if(zi(e))return bu(e)?Z(e):Gr(e);if(wl&&e[wl])return Y(e[wl]());var t=Do(e),n=t==Fe?G:t==qe?X:us;return n(e)}function xu(e){if(!e)return 0===e?e:0;if(e=Mu(e),e===we||e===-we){var t=0>e?-1:1;return t*xe}var n=e%1;return e===e?n?e-n:e:0}function Du(e){return e?yn(xu(e),0,Me):0}function Mu(e){if("number"==typeof e)return e;if(_u(e))return De;if(au(e)){var t=nu(e.valueOf)?e.valueOf():e;e=au(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(Nt,"");var n=kt.test(e);return n||Rt.test(e)?Ln(e.slice(2),n?2:8):Mt.test(e)?De:+e}function ku(e){return $r(e,Yu(e))}function Su(e){return yn(xu(e),-Te,Te)}function Ru(e){if("string"==typeof e)return e;if(null==e)return"";if(_u(e))return ic?ic.call(e):"";var t=e+"";return"0"==t&&1/e==-we?"-0":t}function Iu(e,t){var n=_n(e);return t?vn(n,t):n}function ju(e,t){return N(e,Oo(t,3),An,!0)}function Au(e,t){return N(e,Oo(t,3),Un,!0)}function Vu(e,t){return null==e?e:lc(e,Oo(t),Yu)}function Lu(e,t){return null==e?e:cc(e,Oo(t),Yu)}function Uu(e,t){return e&&An(e,Oo(t))}function Fu(e,t){return e&&Un(e,Oo(t))}function Bu(e){return null==e?[]:Fn(e,zu(e))}function Wu(e){return null==e?[]:Fn(e,Yu(e))}function Hu(e,t,n){var r=null==e?te:Wn(e,t);return r===te?n:r}function Ku(e,t){return null!=e&&ko(e,t,Kn)}function qu(e,t){return null!=e&&ko(e,t,qn)}function zu(e){var t=Wo(e);if(!t&&!zi(e))return nr(e);var n=jo(e),r=!!n,o=n||[],a=o.length;for(var i in e)!Kn(e,i)||r&&("length"==i||z(i,a))||t&&"constructor"==i||o.push(i);return o}function Yu(e){for(var t=-1,n=Wo(e),r=rr(e),o=r.length,a=jo(e),i=!!a,u=a||[],s=u.length;++t<o;){var l=r[t];i&&("length"==l||z(l,s))||"constructor"==l&&(n||!fl.call(e,l))||u.push(l)}return u}function Gu(e,t){var n={};return t=Oo(t,3),An(e,function(e,r,o){n[t(e,r,o)]=e}),n}function $u(e,t){var n={};return t=Oo(t,3),An(e,function(e,r,o){n[r]=t(e,r,o)}),n}function Xu(e,t){return t=Oo(t),dr(e,function(e,n){return!t(e,n)})}function Qu(e,t){return null==e?{}:dr(e,Oo(t))}function Zu(e,t,n){t=Uo(t,e)?[t]:Ar(t);var r=-1,o=t.length;for(o||(e=te,o=1);++r<o;){var a=null==e?te:e[t[r]];a===te&&(r=o,a=n),e=nu(a)?a.call(e):a}return e}function Ju(e,t,n){return null==e?e:_r(e,t,n)}function es(e,t,n,r){return r="function"==typeof r?r:te,null==e?e:_r(e,t,n,r)}function ts(e){return k(e,zu(e))}function ns(e){return k(e,Yu(e))}function rs(e,t,n){var r=Qc(e)||Eu(e);if(t=Oo(t,4),null==n)if(r||au(e)){var o=e.constructor;n=r?Qc(e)?new o:[]:nu(o)?_n(To(e)):{}}else n={};return(r?c:An)(e,function(e,r,o){return t(n,e,r,o)}),n}function os(e,t){return null==e?!0:xr(e,t)}function as(e,t,n){return null==e?e:Dr(e,t,jr(n))}function is(e,t,n,r){return r="function"==typeof r?r:te,null==e?e:Dr(e,t,jr(n),r)}function us(e){return e?R(e,zu(e)):[]}function ss(e){return null==e?[]:R(e,Yu(e))}function ls(e,t,n){return n===te&&(n=t,t=te),n!==te&&(n=Mu(n),n=n===n?n:0),t!==te&&(t=Mu(t),t=t===t?t:0),yn(Mu(e),t,n)}function cs(e,t,n){return t=Mu(t)||0,n===te?(n=t,t=0):n=Mu(n)||0,e=Mu(e),Gn(e,t,n)}function ps(e,t,n){if(n&&"boolean"!=typeof n&&Lo(e,t,n)&&(t=n=te),n===te&&("boolean"==typeof t?(n=t,t=te):"boolean"==typeof e&&(n=e,e=te)),e===te&&t===te?(e=0,t=1):(e=Mu(e)||0,t===te?(t=e,e=0):t=Mu(t)||0),e>t){var r=e;e=t,t=r}if(n||e%1||t%1){var o=Fl();return Ll(e+o*(t-e+Vn("1e-"+((o+"").length-1))),t)}return yr(e,t)}function ds(e){return _p(Ru(e).toLowerCase())}function fs(e){return e=Ru(e),e&&e.replace(jt,B).replace(On,"")}function hs(e,t,n){e=Ru(e),t="string"==typeof t?t:t+"";var r=e.length;return n=n===te?r:yn(xu(n),0,r),n-=t.length,n>=0&&e.indexOf(t,n)==n}function vs(e){return e=Ru(e),e&&ft.test(e)?e.replace(pt,W):e}function ms(e){return e=Ru(e),e&&Et.test(e)?e.replace(_t,"\\$&"):e}function ys(e,t,n){e=Ru(e),t=xu(t);var r=t?Q(e):0;if(!t||r>=t)return e;var o=(t-r)/2;return co(Sl(o),n)+e+co(kl(o),n)}function gs(e,t,n){e=Ru(e),t=xu(t);var r=t?Q(e):0;return t&&t>r?e+co(t-r,n):e}function bs(e,t,n){e=Ru(e),t=xu(t);var r=t?Q(e):0;return t&&t>r?co(t-r,n)+e:e}function _s(e,t,n){return n||null==t?t=0:t&&(t=+t),e=Ru(e).replace(Nt,""),Ul(e,t||(Dt.test(e)?16:10))}function Es(e,t,n){return t=(n?Lo(e,t,n):t===te)?1:xu(t),br(Ru(e),t)}function Ns(){var e=arguments,t=Ru(e[0]);return e.length<3?t:Bl.call(t,e[1],e[2])}function Os(e,t,n){return n&&"number"!=typeof n&&Lo(e,t,n)&&(t=n=te),(n=n===te?Me:n>>>0)?(e=Ru(e),e&&("string"==typeof t||null!=t&&!mu(t))&&(t+="",""==t&&wn.test(e))?Vr(Z(e),0,n):Hl.call(e,t,n)):[]}function Cs(e,t,n){return e=Ru(e),n=yn(xu(n),0,e.length),e.lastIndexOf(t,n)==n}function Ps(e,n,r){var o=t.templateSettings;r&&Lo(e,n,r)&&(n=te),e=Ru(e),n=tp({},n,o,pn);var a,i,u=tp({},n.imports,o.imports,pn),s=zu(u),l=R(u,s),c=0,p=n.interpolate||At,d="__p += '",f=ul((n.escape||At).source+"|"+p.source+"|"+(p===mt?Tt:At).source+"|"+(n.evaluate||At).source+"|$","g"),h="//# sourceURL="+("sourceURL"in n?n.sourceURL:"lodash.templateSources["+ ++Dn+"]")+"\n";e.replace(f,function(t,n,r,o,u,s){return r||(r=o),d+=e.slice(c,s).replace(Vt,H),n&&(a=!0,d+="' +\n__e("+n+") +\n'"),u&&(i=!0,d+="';\n"+u+";\n__p += '"),r&&(d+="' +\n((__t = ("+r+")) == null ? '' : __t) +\n'"),c=s+t.length,t}),d+="';\n";var v=n.variable;v||(d="with (obj) {\n"+d+"\n}\n"),d=(i?d.replace(ut,""):d).replace(st,"$1").replace(lt,"$1;"),d="function("+(v||"obj")+") {\n"+(v?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(a?", __e = _.escape":"")+(i?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+d+"return __p\n}";var m=Ep(function(){return Function(s,h+"return "+d).apply(te,l)});if(m.source=d,eu(m))throw m;return m}function ws(e){return Ru(e).toLowerCase()}function Ts(e){return Ru(e).toUpperCase()}function xs(e,t,n){if(e=Ru(e),!e)return e;if(n||t===te)return e.replace(Nt,"");if(!(t+=""))return e;var r=Z(e),o=Z(t),a=I(r,o),i=j(r,o)+1;return Vr(r,a,i).join("")}function Ds(e,t,n){if(e=Ru(e),!e)return e;if(n||t===te)return e.replace(Ct,"");if(!(t+=""))return e;var r=Z(e),o=j(r,Z(t))+1;return Vr(r,0,o).join("")}function Ms(e,t,n){if(e=Ru(e),!e)return e;if(n||t===te)return e.replace(Ot,"");if(!(t+=""))return e;var r=Z(e),o=I(r,Z(t));return Vr(r,o).join("")}function ks(e,t){var n=be,r=_e;if(au(t)){var o="separator"in t?t.separator:o;n="length"in t?xu(t.length):n,r="omission"in t?Ru(t.omission):r}e=Ru(e);var a=e.length;if(wn.test(e)){var i=Z(e);a=i.length}if(n>=a)return e;var u=n-Q(r);if(1>u)return r;var s=i?Vr(i,0,u).join(""):e.slice(0,u);if(o===te)return s+r;if(i&&(u+=s.length-u),mu(o)){if(e.slice(u).search(o)){var l,c=s;for(o.global||(o=ul(o.source,Ru(xt.exec(o))+"g")),o.lastIndex=0;l=o.exec(c);)var p=l.index;s=s.slice(0,p===te?u:p)}}else if(e.indexOf(o,u)!=u){var d=s.lastIndexOf(o);d>-1&&(s=s.slice(0,d))}return s+r}function Ss(e){return e=Ru(e),e&&dt.test(e)?e.replace(ct,J):e}function Rs(e,t,n){return e=Ru(e),t=n?te:t,t===te&&(t=Tn.test(e)?Pn:Pt),e.match(t)||[]}function Is(e){var t=e?e.length:0,n=Oo();return e=t?m(e,function(e){if("function"!=typeof e[1])throw new sl(oe);return[n(e[0]),e[1]]}):[],ki(function(n){for(var r=-1;++r<t;){var o=e[r];if(u(o[0],this,n))return u(o[1],this,n)}})}function js(e){return bn(gn(e,!0))}function As(e){return function(){return e}}function Vs(e){return e}function Ls(e){return tr("function"==typeof e?e:gn(e,!0))}function Us(e){return ar(gn(e,!0))}function Fs(e,t){return ir(e,gn(t,!0))}function Bs(e,t,n){var r=zu(t),o=Fn(t,r);null!=n||au(t)&&(o.length||!r.length)||(n=t,t=e,e=this,o=Fn(t,zu(t)));var a=!(au(n)&&"chain"in n&&!n.chain),i=nu(e);return c(o,function(n){var r=t[n];e[n]=r,i&&(e.prototype[n]=function(){var t=this.__chain__;if(a||t){var n=e(this.__wrapped__),o=n.__actions__=Gr(this.__actions__);return o.push({func:r,args:arguments,thisArg:e}),n.__chain__=t,n}return r.apply(e,y([this.value()],arguments))})}),e}function Ws(){return zn._===this&&(zn._=yl),this}function Hs(){}function Ks(e){return e=xu(e),ki(function(t){return lr(t,e)})}function qs(e){return Uo(e)?fr(e):hr(e)}function zs(e){return function(t){return null==e?te:Wn(e,t)}}function Ys(e,t){if(e=xu(e),1>e||e>Te)return[];var n=Me,r=Ll(e,Me);t=Oo(t),e-=Me;for(var o=M(r,t);++n<e;)t(n);return o}function Gs(e){return Qc(e)?m(e,$o):_u(e)?[e]:Gr(yc(e))}function $s(e){var t=++hl;return Ru(e)+t}function Xs(e){return e&&e.length?E(e,Vs,Wi):te}function Qs(e,t){return e&&e.length?E(e,Oo(t),Wi):te}function Zs(e){return w(e,Vs)}function Js(e,t){return w(e,Oo(t))}function el(e){return e&&e.length?E(e,Vs,Pu):te}function tl(e,t){return e&&e.length?E(e,Oo(t),Pu):te}function nl(e){return e&&e.length?D(e,Vs):0}function rl(e,t){return e&&e.length?D(e,Oo(t)):0}e=e?Yn.defaults({},e,Yn.pick(zn,xn)):zn;var ol=e.Date,al=e.Error,il=e.Math,ul=e.RegExp,sl=e.TypeError,ll=e.Array.prototype,cl=e.Object.prototype,pl=e.String.prototype,dl=e.Function.prototype.toString,fl=cl.hasOwnProperty,hl=0,vl=dl.call(Object),ml=cl.toString,yl=zn._,gl=ul("^"+dl.call(fl).replace(_t,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),bl=Bn?e.Buffer:te,_l=e.Reflect,El=e.Symbol,Nl=e.Uint8Array,Ol=e.clearTimeout,Cl=_l?_l.enumerate:te,Pl=Object.getOwnPropertySymbols,wl="symbol"==typeof(wl=El&&El.iterator)?wl:te,Tl=Object.create,xl=cl.propertyIsEnumerable,Dl=e.setTimeout,Ml=ll.splice,kl=il.ceil,Sl=il.floor,Rl=Object.getPrototypeOf,Il=e.isFinite,jl=ll.join,Al=Object.keys,Vl=il.max,Ll=il.min,Ul=e.parseInt,Fl=il.random,Bl=pl.replace,Wl=ll.reverse,Hl=pl.split,Kl=Po(e,"DataView"),ql=Po(e,"Map"),zl=Po(e,"Promise"),Yl=Po(e,"Set"),Gl=Po(e,"WeakMap"),$l=Po(Object,"create"),Xl=Gl&&new Gl,Ql=!xl.call({valueOf:1},"valueOf"),Zl={},Jl=Xo(Kl),ec=Xo(ql),tc=Xo(zl),nc=Xo(Yl),rc=Xo(Gl),oc=El?El.prototype:te,ac=oc?oc.valueOf:te,ic=oc?oc.toString:te;t.templateSettings={escape:ht,evaluate:vt,interpolate:mt,variable:"",imports:{_:t}},t.prototype=n.prototype,t.prototype.constructor=t,r.prototype=_n(n.prototype),r.prototype.constructor=r,o.prototype=_n(n.prototype),o.prototype.constructor=o,Ut.prototype=$l?$l(null):cl,Kt.prototype.clear=qt,Kt.prototype["delete"]=zt,Kt.prototype.get=Yt,Kt.prototype.has=Gt,Kt.prototype.set=$t,Xt.prototype.push=Zt,Jt.prototype.clear=en,Jt.prototype["delete"]=tn,Jt.prototype.get=nn,Jt.prototype.has=rn,Jt.prototype.set=on;var uc=Jr(An),sc=Jr(Un,!0),lc=eo(),cc=eo(!0);Cl&&!xl.call({valueOf:1},"valueOf")&&(rr=function(e){return Y(Cl(e))});var pc=Xl?function(e,t){return Xl.set(e,t),e}:Vs,dc=Yl&&2===new Yl([1,2]).size?function(e){return new Yl(e)}:Hs,fc=Xl?function(e){return Xl.get(e)}:Hs,hc=fr("length"); Pl||(xo=function(){return[]});var vc=Pl?function(e){for(var t=[];e;)y(t,xo(e)),e=To(e);return t}:xo;(Kl&&Do(new Kl(new ArrayBuffer(1)))!=Qe||ql&&Do(new ql)!=Fe||zl&&Do(zl.resolve())!=He||Yl&&Do(new Yl)!=qe||Gl&&Do(new Gl)!=Ge)&&(Do=function(e){var t=ml.call(e),n=t==We?e.constructor:te,r=n?Xo(n):te;if(r)switch(r){case Jl:return Qe;case ec:return Fe;case tc:return He;case nc:return qe;case rc:return Ge}return t});var mc=function(){var e=0,t=0;return function(n,r){var o=Wc(),a=Ne-(o-t);if(t=o,a>0){if(++e>=Ee)return n}else e=0;return pc(n,r)}}(),yc=xi(function(e){var t=[];return Ru(e).replace(bt,function(e,n,r,o){t.push(r?o.replace(wt,"$1"):n||e)}),t}),gc=ki(function(e,t){return Yi(e)?Cn(e,jn(t,1,Yi,!0)):[]}),bc=ki(function(e,t){var n=ma(t);return Yi(n)&&(n=te),Yi(e)?Cn(e,jn(t,1,Yi,!0),Oo(n)):[]}),_c=ki(function(e,t){var n=ma(t);return Yi(n)&&(n=te),Yi(e)?Cn(e,jn(t,1,Yi,!0),te,n):[]}),Ec=ki(function(e){var t=m(e,Ir);return t.length&&t[0]===e[0]?$n(t):[]}),Nc=ki(function(e){var t=ma(e),n=m(e,Ir);return t===ma(n)?t=te:n.pop(),n.length&&n[0]===e[0]?$n(n,Oo(t)):[]}),Oc=ki(function(e){var t=ma(e),n=m(e,Ir);return t===ma(n)?t=te:n.pop(),n.length&&n[0]===e[0]?$n(n,te,t):[]}),Cc=ki(ba),Pc=ki(function(e,t){t=m(jn(t,1),String);var n=mn(e,t);return mr(e,t.sort(V)),n}),wc=ki(function(e){return Tr(jn(e,1,Yi,!0))}),Tc=ki(function(e){var t=ma(e);return Yi(t)&&(t=te),Tr(jn(e,1,Yi,!0),Oo(t))}),xc=ki(function(e){var t=ma(e);return Yi(t)&&(t=te),Tr(jn(e,1,Yi,!0),te,t)}),Dc=ki(function(e,t){return Yi(e)?Cn(e,t):[]}),Mc=ki(function(e){return Sr(f(e,Yi))}),kc=ki(function(e){var t=ma(e);return Yi(t)&&(t=te),Sr(f(e,Yi),Oo(t))}),Sc=ki(function(e){var t=ma(e);return Yi(t)&&(t=te),Sr(f(e,Yi),te,t)}),Rc=ki(Ba),Ic=ki(function(e){var t=e.length,n=t>1?e[t-1]:te;return n="function"==typeof n?(e.pop(),n):te,Wa(e,n)}),jc=ki(function(e){e=jn(e,1);var t=e.length,n=t?e[0]:0,a=this.__wrapped__,i=function(t){return mn(t,e)};return!(t>1||this.__actions__.length)&&a instanceof o&&z(n)?(a=a.slice(n,+n+(t?1:0)),a.__actions__.push({func:Ya,args:[i],thisArg:te}),new r(a,this.__chain__).thru(function(e){return t&&!e.length&&e.push(te),e})):this.thru(i)}),Ac=Qr(function(e,t,n){fl.call(e,n)?++e[n]:e[n]=1}),Vc=Qr(function(e,t,n){fl.call(e,n)?e[n].push(t):e[n]=[t]}),Lc=ki(function(e,t,n){var r=-1,o="function"==typeof t,a=Uo(t),i=zi(e)?Array(e.length):[];return uc(e,function(e){var s=o?t:a&&null!=e?e[t]:te;i[++r]=s?u(s,e,n):Qn(e,t,n)}),i}),Uc=Qr(function(e,t,n){e[n]=t}),Fc=Qr(function(e,t,n){e[n?0:1].push(t)},function(){return[[],[]]}),Bc=ki(function(e,t){if(null==e)return[];var n=t.length;return n>1&&Lo(e,t[0],t[1])?t=[]:n>2&&Lo(t[0],t[1],t[2])&&(t=[t[0]]),t=1==t.length&&Qc(t[0])?t[0]:jn(t,1,Vo),cr(e,t,[])}),Wc=ol.now,Hc=ki(function(e,t,n){var r=ue;if(n.length){var o=$(n,wo(Hc));r|=de}return mo(e,r,t,n,o)}),Kc=ki(function(e,t,n){var r=ue|se;if(n.length){var o=$(n,wo(Kc));r|=de}return mo(t,r,e,n,o)}),qc=ki(function(e,t){return En(e,1,t)}),zc=ki(function(e,t,n){return En(e,Mu(t)||0,n)});xi.Cache=Kt;var Yc=ki(function(e,t){t=1==t.length&&Qc(t[0])?m(t[0],S(Oo())):m(jn(t,1,Vo),S(Oo()));var n=t.length;return ki(function(r){for(var o=-1,a=Ll(r.length,n);++o<a;)r[o]=t[o].call(this,r[o]);return u(e,this,r)})}),Gc=ki(function(e,t){var n=$(t,wo(Gc));return mo(e,de,te,t,n)}),$c=ki(function(e,t){var n=$(t,wo($c));return mo(e,fe,te,t,n)}),Xc=ki(function(e,t){return mo(e,ve,te,te,te,jn(t,1))}),Qc=Array.isArray,Zc=bl?function(e){return e instanceof bl}:As(!1),Jc=Zr(function(e,t){if(Ql||Wo(t)||zi(t))return void $r(t,zu(t),e);for(var n in t)fl.call(t,n)&&fn(e,n,t[n])}),ep=Zr(function(e,t){if(Ql||Wo(t)||zi(t))return void $r(t,Yu(t),e);for(var n in t)fn(e,n,t[n])}),tp=Zr(function(e,t,n,r){$r(t,Yu(t),e,r)}),np=Zr(function(e,t,n,r){$r(t,zu(t),e,r)}),rp=ki(function(e,t){return mn(e,jn(t,1))}),op=ki(function(e){return e.push(te,pn),u(tp,te,e)}),ap=ki(function(e){return e.push(te,zo),u(cp,te,e)}),ip=so(function(e,t,n){e[t]=n},As(Vs)),up=so(function(e,t,n){fl.call(e,t)?e[t].push(n):e[t]=[n]},Oo),sp=ki(Qn),lp=Zr(function(e,t,n){ur(e,t,n)}),cp=Zr(function(e,t,n,r){ur(e,t,n,r)}),pp=ki(function(e,t){return null==e?{}:(t=m(jn(t,1),$o),pr(e,Cn(Eo(e),t)))}),dp=ki(function(e,t){return null==e?{}:pr(e,jn(t,1))}),fp=ro(function(e,t,n){return t=t.toLowerCase(),e+(n?ds(t):t)}),hp=ro(function(e,t,n){return e+(n?"-":"")+t.toLowerCase()}),vp=ro(function(e,t,n){return e+(n?" ":"")+t.toLowerCase()}),mp=no("toLowerCase"),yp=ro(function(e,t,n){return e+(n?"_":"")+t.toLowerCase()}),gp=ro(function(e,t,n){return e+(n?" ":"")+_p(t)}),bp=ro(function(e,t,n){return e+(n?" ":"")+t.toUpperCase()}),_p=no("toUpperCase"),Ep=ki(function(e,t){try{return u(e,te,t)}catch(n){return eu(n)?n:new al(n)}}),Np=ki(function(e,t){return c(jn(t,1),function(t){e[t]=Hc(e[t],e)}),e}),Op=io(),Cp=io(!0),Pp=ki(function(e,t){return function(n){return Qn(n,e,t)}}),wp=ki(function(e,t){return function(n){return Qn(e,n,t)}}),Tp=lo(m),xp=lo(d),Dp=lo(_),Mp=fo(),kp=fo(!0),Sp=F(function(e,t){return e+t}),Rp=vo("ceil"),Ip=F(function(e,t){return e/t}),jp=vo("floor"),Ap=F(function(e,t){return e*t}),Vp=vo("round"),Lp=F(function(e,t){return e-t});return t.after=Ei,t.ary=Ni,t.assign=Jc,t.assignIn=ep,t.assignInWith=tp,t.assignWith=np,t.at=rp,t.before=Oi,t.bind=Hc,t.bindAll=Np,t.bindKey=Kc,t.castArray=Ai,t.chain=qa,t.chunk=Zo,t.compact=Jo,t.concat=ea,t.cond=Is,t.conforms=js,t.constant=As,t.countBy=Ac,t.create=Iu,t.curry=Ci,t.curryRight=Pi,t.debounce=wi,t.defaults=op,t.defaultsDeep=ap,t.defer=qc,t.delay=zc,t.difference=gc,t.differenceBy=bc,t.differenceWith=_c,t.drop=ta,t.dropRight=na,t.dropRightWhile=ra,t.dropWhile=oa,t.fill=aa,t.filter=ni,t.flatMap=ai,t.flatMapDeep=ii,t.flatMapDepth=ui,t.flatten=sa,t.flattenDeep=la,t.flattenDepth=ca,t.flip=Ti,t.flow=Op,t.flowRight=Cp,t.fromPairs=pa,t.functions=Bu,t.functionsIn=Wu,t.groupBy=Vc,t.initial=ha,t.intersection=Ec,t.intersectionBy=Nc,t.intersectionWith=Oc,t.invert=ip,t.invertBy=up,t.invokeMap=Lc,t.iteratee=Ls,t.keyBy=Uc,t.keys=zu,t.keysIn=Yu,t.map=pi,t.mapKeys=Gu,t.mapValues=$u,t.matches=Us,t.matchesProperty=Fs,t.memoize=xi,t.merge=lp,t.mergeWith=cp,t.method=Pp,t.methodOf=wp,t.mixin=Bs,t.negate=Di,t.nthArg=Ks,t.omit=pp,t.omitBy=Xu,t.once=Mi,t.orderBy=di,t.over=Tp,t.overArgs=Yc,t.overEvery=xp,t.overSome=Dp,t.partial=Gc,t.partialRight=$c,t.partition=Fc,t.pick=dp,t.pickBy=Qu,t.property=qs,t.propertyOf=zs,t.pull=Cc,t.pullAll=ba,t.pullAllBy=_a,t.pullAllWith=Ea,t.pullAt=Pc,t.range=Mp,t.rangeRight=kp,t.rearg=Xc,t.reject=vi,t.remove=Na,t.rest=ki,t.reverse=Oa,t.sampleSize=yi,t.set=Ju,t.setWith=es,t.shuffle=gi,t.slice=Ca,t.sortBy=Bc,t.sortedUniq=ka,t.sortedUniqBy=Sa,t.split=Os,t.spread=Si,t.tail=Ra,t.take=Ia,t.takeRight=ja,t.takeRightWhile=Aa,t.takeWhile=Va,t.tap=za,t.throttle=Ri,t.thru=Ya,t.toArray=Tu,t.toPairs=ts,t.toPairsIn=ns,t.toPath=Gs,t.toPlainObject=ku,t.transform=rs,t.unary=Ii,t.union=wc,t.unionBy=Tc,t.unionWith=xc,t.uniq=La,t.uniqBy=Ua,t.uniqWith=Fa,t.unset=os,t.unzip=Ba,t.unzipWith=Wa,t.update=as,t.updateWith=is,t.values=us,t.valuesIn=ss,t.without=Dc,t.words=Rs,t.wrap=ji,t.xor=Mc,t.xorBy=kc,t.xorWith=Sc,t.zip=Rc,t.zipObject=Ha,t.zipObjectDeep=Ka,t.zipWith=Ic,t.entries=ts,t.entriesIn=ns,t.extend=ep,t.extendWith=tp,Bs(t,t),t.add=Sp,t.attempt=Ep,t.camelCase=fp,t.capitalize=ds,t.ceil=Rp,t.clamp=ls,t.clone=Vi,t.cloneDeep=Ui,t.cloneDeepWith=Fi,t.cloneWith=Li,t.deburr=fs,t.divide=Ip,t.endsWith=hs,t.eq=Bi,t.escape=vs,t.escapeRegExp=ms,t.every=ti,t.find=ri,t.findIndex=ia,t.findKey=ju,t.findLast=oi,t.findLastIndex=ua,t.findLastKey=Au,t.floor=jp,t.forEach=si,t.forEachRight=li,t.forIn=Vu,t.forInRight=Lu,t.forOwn=Uu,t.forOwnRight=Fu,t.get=Hu,t.gt=Wi,t.gte=Hi,t.has=Ku,t.hasIn=qu,t.head=da,t.identity=Vs,t.includes=ci,t.indexOf=fa,t.inRange=cs,t.invoke=sp,t.isArguments=Ki,t.isArray=Qc,t.isArrayBuffer=qi,t.isArrayLike=zi,t.isArrayLikeObject=Yi,t.isBoolean=Gi,t.isBuffer=Zc,t.isDate=$i,t.isElement=Xi,t.isEmpty=Qi,t.isEqual=Zi,t.isEqualWith=Ji,t.isError=eu,t.isFinite=tu,t.isFunction=nu,t.isInteger=ru,t.isLength=ou,t.isMap=uu,t.isMatch=su,t.isMatchWith=lu,t.isNaN=cu,t.isNative=pu,t.isNil=fu,t.isNull=du,t.isNumber=hu,t.isObject=au,t.isObjectLike=iu,t.isPlainObject=vu,t.isRegExp=mu,t.isSafeInteger=yu,t.isSet=gu,t.isString=bu,t.isSymbol=_u,t.isTypedArray=Eu,t.isUndefined=Nu,t.isWeakMap=Ou,t.isWeakSet=Cu,t.join=va,t.kebabCase=hp,t.last=ma,t.lastIndexOf=ya,t.lowerCase=vp,t.lowerFirst=mp,t.lt=Pu,t.lte=wu,t.max=Xs,t.maxBy=Qs,t.mean=Zs,t.meanBy=Js,t.min=el,t.minBy=tl,t.multiply=Ap,t.nth=ga,t.noConflict=Ws,t.noop=Hs,t.now=Wc,t.pad=ys,t.padEnd=gs,t.padStart=bs,t.parseInt=_s,t.random=ps,t.reduce=fi,t.reduceRight=hi,t.repeat=Es,t.replace=Ns,t.result=Zu,t.round=Vp,t.runInContext=ee,t.sample=mi,t.size=bi,t.snakeCase=yp,t.some=_i,t.sortedIndex=Pa,t.sortedIndexBy=wa,t.sortedIndexOf=Ta,t.sortedLastIndex=xa,t.sortedLastIndexBy=Da,t.sortedLastIndexOf=Ma,t.startCase=gp,t.startsWith=Cs,t.subtract=Lp,t.sum=nl,t.sumBy=rl,t.template=Ps,t.times=Ys,t.toInteger=xu,t.toLength=Du,t.toLower=ws,t.toNumber=Mu,t.toSafeInteger=Su,t.toString=Ru,t.toUpper=Ts,t.trim=xs,t.trimEnd=Ds,t.trimStart=Ms,t.truncate=ks,t.unescape=Ss,t.uniqueId=$s,t.upperCase=bp,t.upperFirst=_p,t.each=si,t.eachRight=li,t.first=da,Bs(t,function(){var e={};return An(t,function(n,r){fl.call(t.prototype,r)||(e[r]=n)}),e}(),{chain:!1}),t.VERSION=ne,c(["bind","bindKey","curry","curryRight","partial","partialRight"],function(e){t[e].placeholder=t}),c(["drop","take"],function(e,t){o.prototype[e]=function(n){var r=this.__filtered__;if(r&&!t)return new o(this);n=n===te?1:Vl(xu(n),0);var a=this.clone();return r?a.__takeCount__=Ll(n,a.__takeCount__):a.__views__.push({size:Ll(n,Me),type:e+(a.__dir__<0?"Right":"")}),a},o.prototype[e+"Right"]=function(t){return this.reverse()[e](t).reverse()}}),c(["filter","map","takeWhile"],function(e,t){var n=t+1,r=n==Oe||n==Pe;o.prototype[e]=function(e){var t=this.clone();return t.__iteratees__.push({iteratee:Oo(e,3),type:n}),t.__filtered__=t.__filtered__||r,t}}),c(["head","last"],function(e,t){var n="take"+(t?"Right":"");o.prototype[e]=function(){return this[n](1).value()[0]}}),c(["initial","tail"],function(e,t){var n="drop"+(t?"":"Right");o.prototype[e]=function(){return this.__filtered__?new o(this):this[n](1)}}),o.prototype.compact=function(){return this.filter(Vs)},o.prototype.find=function(e){return this.filter(e).head()},o.prototype.findLast=function(e){return this.reverse().find(e)},o.prototype.invokeMap=ki(function(e,t){return"function"==typeof e?new o(this):this.map(function(n){return Qn(n,e,t)})}),o.prototype.reject=function(e){return e=Oo(e,3),this.filter(function(t){return!e(t)})},o.prototype.slice=function(e,t){e=xu(e);var n=this;return n.__filtered__&&(e>0||0>t)?new o(n):(0>e?n=n.takeRight(-e):e&&(n=n.drop(e)),t!==te&&(t=xu(t),n=0>t?n.dropRight(-t):n.take(t-e)),n)},o.prototype.takeRightWhile=function(e){return this.reverse().takeWhile(e).reverse()},o.prototype.toArray=function(){return this.take(Me)},An(o.prototype,function(e,n){var a=/^(?:filter|find|map|reject)|While$/.test(n),i=/^(?:head|last)$/.test(n),u=t[i?"take"+("last"==n?"Right":""):n],s=i||/^find/.test(n);u&&(t.prototype[n]=function(){var n=this.__wrapped__,l=i?[1]:arguments,c=n instanceof o,p=l[0],d=c||Qc(n),f=function(e){var n=u.apply(t,y([e],l));return i&&h?n[0]:n};d&&a&&"function"==typeof p&&1!=p.length&&(c=d=!1);var h=this.__chain__,v=!!this.__actions__.length,m=s&&!h,g=c&&!v;if(!s&&d){n=g?n:new o(this);var b=e.apply(n,l);return b.__actions__.push({func:Ya,args:[f],thisArg:te}),new r(b,h)}return m&&g?e.apply(this,l):(b=this.thru(f),m?i?b.value()[0]:b.value():b)})}),c(["pop","push","shift","sort","splice","unshift"],function(e){var n=ll[e],r=/^(?:push|sort|unshift)$/.test(e)?"tap":"thru",o=/^(?:pop|shift)$/.test(e);t.prototype[e]=function(){var e=arguments;if(o&&!this.__chain__){var t=this.value();return n.apply(Qc(t)?t:[],e)}return this[r](function(t){return n.apply(Qc(t)?t:[],e)})}}),An(o.prototype,function(e,n){var r=t[n];if(r){var o=r.name+"",a=Zl[o]||(Zl[o]=[]);a.push({name:n,func:r})}}),Zl[uo(te,se).name]=[{name:"wrapper",func:te}],o.prototype.clone=A,o.prototype.reverse=It,o.prototype.value=Lt,t.prototype.at=jc,t.prototype.chain=Ga,t.prototype.commit=$a,t.prototype.next=Xa,t.prototype.plant=Za,t.prototype.reverse=Ja,t.prototype.toJSON=t.prototype.valueOf=t.prototype.value=ei,wl&&(t.prototype[wl]=Qa),t}var te,ne="4.11.1",re=200,oe="Expected a function",ae="__lodash_hash_undefined__",ie="__lodash_placeholder__",ue=1,se=2,le=4,ce=8,pe=16,de=32,fe=64,he=128,ve=256,me=512,ye=1,ge=2,be=30,_e="...",Ee=150,Ne=16,Oe=1,Ce=2,Pe=3,we=1/0,Te=9007199254740991,xe=1.7976931348623157e308,De=NaN,Me=4294967295,ke=Me-1,Se=Me>>>1,Re="[object Arguments]",Ie="[object Array]",je="[object Boolean]",Ae="[object Date]",Ve="[object Error]",Le="[object Function]",Ue="[object GeneratorFunction]",Fe="[object Map]",Be="[object Number]",We="[object Object]",He="[object Promise]",Ke="[object RegExp]",qe="[object Set]",ze="[object String]",Ye="[object Symbol]",Ge="[object WeakMap]",$e="[object WeakSet]",Xe="[object ArrayBuffer]",Qe="[object DataView]",Ze="[object Float32Array]",Je="[object Float64Array]",et="[object Int8Array]",tt="[object Int16Array]",nt="[object Int32Array]",rt="[object Uint8Array]",ot="[object Uint8ClampedArray]",at="[object Uint16Array]",it="[object Uint32Array]",ut=/\b__p \+= '';/g,st=/\b(__p \+=) '' \+/g,lt=/(__e\(.*?\)|\b__t\)) \+\n'';/g,ct=/&(?:amp|lt|gt|quot|#39|#96);/g,pt=/[&<>"'`]/g,dt=RegExp(ct.source),ft=RegExp(pt.source),ht=/<%-([\s\S]+?)%>/g,vt=/<%([\s\S]+?)%>/g,mt=/<%=([\s\S]+?)%>/g,yt=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,gt=/^\w*$/,bt=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]/g,_t=/[\\^$.*+?()[\]{}|]/g,Et=RegExp(_t.source),Nt=/^\s+|\s+$/g,Ot=/^\s+/,Ct=/\s+$/,Pt=/[a-zA-Z0-9]+/g,wt=/\\(\\)?/g,Tt=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,xt=/\w*$/,Dt=/^0x/i,Mt=/^[-+]0x[0-9a-f]+$/i,kt=/^0b[01]+$/i,St=/^\[object .+?Constructor\]$/,Rt=/^0o[0-7]+$/i,It=/^(?:0|[1-9]\d*)$/,jt=/[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g,At=/($^)/,Vt=/['\n\r\u2028\u2029\\]/g,Lt="\\ud800-\\udfff",Ut="\\u0300-\\u036f\\ufe20-\\ufe23",Ft="\\u20d0-\\u20f0",Bt="\\u2700-\\u27bf",Wt="a-z\\xdf-\\xf6\\xf8-\\xff",Ht="\\xac\\xb1\\xd7\\xf7",Kt="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",qt="\\u2018\\u2019\\u201c\\u201d",zt=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",Yt="A-Z\\xc0-\\xd6\\xd8-\\xde",Gt="\\ufe0e\\ufe0f",$t=Ht+Kt+qt+zt,Xt="['’]",Qt="["+Lt+"]",Zt="["+$t+"]",Jt="["+Ut+Ft+"]",en="\\d+",tn="["+Bt+"]",nn="["+Wt+"]",rn="[^"+Lt+$t+en+Bt+Wt+Yt+"]",on="\\ud83c[\\udffb-\\udfff]",an="(?:"+Jt+"|"+on+")",un="[^"+Lt+"]",sn="(?:\\ud83c[\\udde6-\\uddff]){2}",ln="[\\ud800-\\udbff][\\udc00-\\udfff]",cn="["+Yt+"]",pn="\\u200d",dn="(?:"+nn+"|"+rn+")",fn="(?:"+cn+"|"+rn+")",hn="(?:"+Xt+"(?:d|ll|m|re|s|t|ve))?",vn="(?:"+Xt+"(?:D|LL|M|RE|S|T|VE))?",mn=an+"?",yn="["+Gt+"]?",gn="(?:"+pn+"(?:"+[un,sn,ln].join("|")+")"+yn+mn+")*",bn=yn+mn+gn,_n="(?:"+[tn,sn,ln].join("|")+")"+bn,En="(?:"+[un+Jt+"?",Jt,sn,ln,Qt].join("|")+")",Nn=RegExp(Xt,"g"),On=RegExp(Jt,"g"),Cn=RegExp(on+"(?="+on+")|"+En+bn,"g"),Pn=RegExp([cn+"?"+nn+"+"+hn+"(?="+[Zt,cn,"$"].join("|")+")",fn+"+"+vn+"(?="+[Zt,cn+dn,"$"].join("|")+")",cn+"?"+dn+"+"+hn,cn+"+"+vn,en,_n].join("|"),"g"),wn=RegExp("["+pn+Lt+Ut+Ft+Gt+"]"),Tn=/[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,xn=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","Reflect","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],Dn=-1,Mn={};Mn[Ze]=Mn[Je]=Mn[et]=Mn[tt]=Mn[nt]=Mn[rt]=Mn[ot]=Mn[at]=Mn[it]=!0,Mn[Re]=Mn[Ie]=Mn[Xe]=Mn[je]=Mn[Qe]=Mn[Ae]=Mn[Ve]=Mn[Le]=Mn[Fe]=Mn[Be]=Mn[We]=Mn[Ke]=Mn[qe]=Mn[ze]=Mn[Ge]=!1;var kn={};kn[Re]=kn[Ie]=kn[Xe]=kn[Qe]=kn[je]=kn[Ae]=kn[Ze]=kn[Je]=kn[et]=kn[tt]=kn[nt]=kn[Fe]=kn[Be]=kn[We]=kn[Ke]=kn[qe]=kn[ze]=kn[Ye]=kn[rt]=kn[ot]=kn[at]=kn[it]=!0,kn[Ve]=kn[Le]=kn[Ge]=!1;var Sn={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss"},Rn={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","`":"&#96;"},In={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'","&#96;":"`"},jn={"function":!0,object:!0},An={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},Vn=parseFloat,Ln=parseInt,Un=jn[typeof t]&&t&&!t.nodeType?t:te,Fn=jn[typeof e]&&e&&!e.nodeType?e:te,Bn=Fn&&Fn.exports===Un?Un:te,Wn=A(Un&&Fn&&"object"==typeof o&&o),Hn=A(jn[typeof self]&&self),Kn=A(jn[typeof window]&&window),qn=A(jn[typeof this]&&this),zn=Wn||Kn!==(qn&&qn.window)&&Kn||Hn||qn||Function("return this")(),Yn=ee();(Kn||Hn||{})._=Yn,r=function(){return Yn}.call(t,n,t,e),!(r!==te&&(e.exports=r))}).call(this)}).call(t,n(190)(e),function(){return this}())},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children=[],e.webpackPolyfill=1),e}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Object.defineProperty(t,"__esModule",{value:!0});var 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},i=n(2),u=r(i),s=n(159),l=r(s),c=n(160),p=r(c),d=u["default"].createClass({displayName:"Tooltip",mixins:[p["default"]],propTypes:{placement:u["default"].PropTypes.oneOf(["top","right","bottom","left"]),positionLeft:u["default"].PropTypes.number,positionTop:u["default"].PropTypes.number,classPrefix:u["default"].PropTypes.string,arrowOffsetLeft:u["default"].PropTypes.oneOfType([u["default"].PropTypes.number,u["default"].PropTypes.string]),arrowOffsetTop:u["default"].PropTypes.oneOfType([u["default"].PropTypes.number,u["default"].PropTypes.string]),title:u["default"].PropTypes.node},getDefaultProps:function(){return{placement:"right",classPrefix:"tooltip"}},render:function(){var e=this.props,t=e.placement,n=e.className,r=e.positionLeft,i=e.positionTop,s=e.children,c=(0,l["default"])(o({tooltip:!0},t,!0),n),p={left:r,top:i},d={left:this.props.arrowOffsetLeft,top:this.props.arrowOffsetTop};return u["default"].createElement("div",a({role:"tooltip"},this.props,{className:c,style:p}),u["default"].createElement("div",{className:this.prefix("arrow"),style:d}),u["default"].createElement("div",{className:this.prefix("inner")},s))}});t["default"]=d},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Object.defineProperty(t,"__esModule",{value:!0});var 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},i=n(2),u=r(i),s=n(159),l=r(s),c=n(160),p=r(c),d=u["default"].createClass({displayName:"Popover",mixins:[p["default"]],propTypes:{placement:u["default"].PropTypes.oneOf(["top","right","bottom","left"]),classPrefix:u["default"].PropTypes.string,title:u["default"].PropTypes.node},getDefaultProps:function(){return{classPrefix:"popover",placement:"right"}},render:function(){var e=(0,l["default"])(o({popover:!0},this.props.placement,!0),this.props.className),t=a({display:"block"},this.props.style);return u["default"].createElement("div",a({role:"popover"},this.props,{className:e,style:t}),u["default"].createElement("div",{className:"arrow"}),u["default"].createElement("h3",{className:this.prefix("title")},this.props.title),u["default"].createElement("div",{className:this.prefix("content")},this.props.children))}});t["default"]=d},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var 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},i=n(2),u=r(i),s=n(161),l=r(s),c=n(159),p=r(c),d=n(189),f=n(194),h=r(f),v=n(175),m=r(v),y=n(188),g=r(y),b=n(164),_=r(b),E=n(160),N=r(E),O=n(185),C=r(O),P=n(196),w=r(P),T=n(197),x=r(T),D=n(198),M=r(D),k=n(199),S=r(k),R=n(200),I=r(R),j=n(177),A=r(j),V=300,L=150,U=u["default"].createClass({displayName:"Modal",mixins:[N["default"]],propTypes:a({},h["default"].propTypes,w["default"].propTypes,{backdrop:u["default"].PropTypes.oneOf(["static",!0,!1]),keyboard:u["default"].PropTypes.bool,animation:u["default"].PropTypes.bool,dialogComponentClass:_["default"],dialogComponent:(0,g["default"])(_["default"],"Use `dialogComponentClass`."),autoFocus:u["default"].PropTypes.bool,enforceFocus:u["default"].PropTypes.bool,show:u["default"].PropTypes.bool,autoResizeHeight:u["default"].PropTypes.bool,onHide:u["default"].PropTypes.func,onEnter:u["default"].PropTypes.func,onEntering:u["default"].PropTypes.func,onEntered:u["default"].PropTypes.func,onExit:u["default"].PropTypes.func,onExiting:u["default"].PropTypes.func,onExited:u["default"].PropTypes.func,dialogClassName:u["default"].PropTypes.string}),childContextTypes:{onModalHide:u["default"].PropTypes.func},getDefaultProps:function(){return a({},h["default"].defaultProps,{classPrefix:"modal",animation:!0,dialogComponentClass:w["default"],autoResizeHeight:!0})},getInitialState:function(){return{modalStyles:{},bodyStyles:{}}},getChildContext:function(){return{onModalHide:this.props.onHide}},componentWillUnmount:function(){m["default"].off(window,"resize",this.handleWindowResize)},render:function(){var e=this,t=this.props,n=t.className,r=t.children,i=t.dialogClassName,s=t.autoResizeHeight,l=t.animation,c=o(t,["className","children","dialogClassName","autoResizeHeight","animation"]),f=this.state,v=f.modalStyles,m=f.bodyStyles,y={"in":c.show&&!l},g=c.dialogComponent||c.dialogComponentClass,b=(0,d.pick)(c,Object.keys(h["default"].propTypes).concat(["onExit","onExiting","onEnter","onEntered"])),_=s?u["default"].Children.map(r,function(e,t){return"ModalBody"===e.type.displayName?u["default"].cloneElement(e,{key:t,style:m},e.props.children):e}):r,E=u["default"].createElement(g,a({key:"modal",ref:function(t){return e._modal=t},style:v,className:(0,p["default"])(n,y),dialogClassName:i,onClick:c.backdrop===!0?this.handleDialogClick:null},c),_);return u["default"].createElement(h["default"],a({show:c.show,ref:function(t){e._wrapper=t&&t.refs.modal,e._backdrop=t&&t.refs.backdrop},onEntering:this.handleShow,onExited:this.handleHide,backdropClassName:(0,p["default"])(this.prefix("backdrop"),y),containerClassName:this.prefix("open"),transition:l?C["default"]:void 0,dialogTransitionTimeout:V,backdropTransitionTimeout:L},b),E)},handleShow:function(){if(m["default"].on(window,"resize",this.handleWindowResize),this.setState(this.getStyles()),this.props.onEntering){var e;(e=this.props).onEntering.apply(e,arguments)}},handleHide:function(){if(m["default"].off(window,"resize",this.handleWindowResize),this.props.onExited){var e;(e=this.props).onExited.apply(e,arguments)}},handleDialogClick:function(e){e.target===e.currentTarget&&this.props.onHide()},handleWindowResize:function(){this.setState(this.getStyles())},getStyles:function(){if(!j.canUseDOM)return{};var e=l["default"].findDOMNode(this._modal),t=(0,j.ownerDocument)(e),n=e.scrollHeight,r=(0,j.isOverflowing)(l["default"].findDOMNode(this.props.container||t.body)),o=n>t.documentElement.clientHeight,a={modalStyles:{paddingRight:r&&!o?(0,j.getScrollbarSize)():void 0,paddingLeft:!r&&o?(0,j.getScrollbarSize)():void 0}};if(this.props.autoResizeHeight){var i=200,u=A["default"].getHeight(window)-i,s=n>=u?u:n;a.bodyStyles={maxHeight:s,overflow:"auto"}}return a}});U.Body=x["default"],U.Header=M["default"],U.Title=S["default"],U.Footer=I["default"],U.Dialog=w["default"],t["default"]=U},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var 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},i=n(2),u=r(i),s=n(182),l=r(s),c=n(164),p=r(c),d=n(181),f=r(d),h=n(195),v=r(h),m=n(175),y=r(m),g=n(177),b=new v["default"],_=u["default"].createClass({displayName:"Modal",propTypes:a({},f["default"].propTypes,{show:u["default"].PropTypes.bool,container:u["default"].PropTypes.oneOfType([l["default"],u["default"].PropTypes.func]),onShow:u["default"].PropTypes.func,onHide:u["default"].PropTypes.func,backdrop:u["default"].PropTypes.oneOfType([u["default"].PropTypes.bool,u["default"].PropTypes.oneOf(["static"])]),onEscapeKeyUp:u["default"].PropTypes.func,onBackdropClick:u["default"].PropTypes.func,backdropStyle:u["default"].PropTypes.object,backdropClassName:u["default"].PropTypes.string,containerClassName:u["default"].PropTypes.string,keyboard:u["default"].PropTypes.bool,transition:p["default"],dialogTransitionTimeout:u["default"].PropTypes.number,backdropTransitionTimeout:u["default"].PropTypes.number,autoFocus:u["default"].PropTypes.bool,enforceFocus:u["default"].PropTypes.bool,onEnter:u["default"].PropTypes.func,onEntering:u["default"].PropTypes.func,onEntered:u["default"].PropTypes.func,onExit:u["default"].PropTypes.func,onExiting:u["default"].PropTypes.func,onExited:u["default"].PropTypes.func}),getDefaultProps:function(){var e=function(){};return{show:!1,backdrop:!0,keyboard:!0,autoFocus:!0,enforceFocus:!0,onHide:e}},getInitialState:function(){return{exited:!this.props.show}},render:function(){var e=this.props,t=(e.children,e.transition),n=e.backdrop,r=e.dialogTransitionTimeout,a=o(e,["children","transition","backdrop","dialogTransitionTimeout"]),s=a.onExit,l=a.onExiting,c=a.onEnter,p=a.onEntering,d=a.onEntered,h=!!a.show,v=u["default"].Children.only(this.props.children),m=h||t&&!this.state.exited;if(!m)return null;var y=v.props,g=y.role,b=y.tabIndex;return void 0!==g&&void 0!==b||(v=(0,i.cloneElement)(v,{role:void 0===g?"document":g,tabIndex:null===b?"-1":b})),t&&(v=u["default"].createElement(t,{transitionAppear:!0,unmountOnExit:!0,"in":h,timeout:r,onExit:s,onExiting:l,onExited:this.handleHidden,onEnter:c,onEntering:p,onEntered:d},v)),u["default"].createElement(f["default"],{ref:this.setMountNode,container:a.container},u["default"].createElement("div",{ref:"modal",role:a.role||"dialog",style:a.style,className:a.className},n&&this.renderBackdrop(),v))},renderBackdrop:function(){var e=this.props,t=e.transition,n=e.backdropTransitionTimeout,r=u["default"].createElement("div",{ref:"backdrop",style:this.props.backdropStyle,className:this.props.backdropClassName,onClick:this.handleBackdropClick});return t&&(r=u["default"].createElement(t,{transitionAppear:!0,"in":this.props.show,timeout:n},r)),r},componentWillReceiveProps:function(e){e.show?this.setState({exited:!1}):e.transition||this.setState({exited:!0})},componentWillUpdate:function(e){!this.props.show&&e.show&&this.checkForFocus()},componentDidMount:function(){this.props.show&&this.onShow()},componentDidUpdate:function(e){var t=this.props.transition;!e.show||this.props.show||t?!e.show&&this.props.show&&this.onShow():this.onHide()},componentWillUnmount:function(){var e=this.props,t=e.show,n=e.transition;(t||n&&!this.state.exited)&&this.onHide()},onShow:function(){var e=(0,g.ownerDocument)(this),t=(0,g.getContainer)(this.props.container,e.body);b.add(this,t,this.props.containerClassName),this._onDocumentKeyupListener=y["default"].on(e,"keyup",this.handleDocumentKeyUp),this._onFocusinListener=y["default"].onFocus(this.enforceFocus),this.focus(),this.props.onShow&&this.props.onShow()},onHide:function(){b.remove(this),this._onDocumentKeyupListener.off(),this._onFocusinListener.off(),this.restoreLastFocus()},setMountNode:function(e){this.mountNode=e?e.getMountNode():e},handleHidden:function(){if(this.setState({exited:!0}),this.onHide(),this.props.onExited){var e;(e=this.props).onExited.apply(e,arguments)}},handleBackdropClick:function(e){e.target===e.currentTarget&&(this.props.onBackdropClick&&this.props.onBackdropClick(e),this.props.backdrop===!0&&this.props.onHide())},handleDocumentKeyUp:function(e){this.props.keyboard&&27===e.keyCode&&this.isTopModal()&&(this.props.onEscapeKeyUp&&this.props.onEscapeKeyUp(e),this.props.onHide())},checkForFocus:function(){g.canUseDom&&(this.lastFocus=(0,g.activeElement)())},focus:function(){var e=this.props.autoFocus,t=this.getDialogElement(),n=(0,g.activeElement)((0,g.ownerDocument)(this)),r=n&&(0,g.contains)(t,n);t&&e&&!r&&(this.lastFocus=n,t.hasAttribute("tabIndex")||(t.setAttribute("tabIndex",-1),new Error(!1,'The modal content node does not accept focus. For the benefit of assistive technologies, the tabIndex of the node is being set to "-1".')),t.focus())},restoreLastFocus:function(){this.lastFocus&&this.lastFocus.focus&&(this.lastFocus.focus(),this.lastFocus=null)},enforceFocus:function E(){var E=this.props.enforceFocus;if(E&&this.isMounted()&&this.isTopModal()){var e=(0,g.activeElement)((0,g.ownerDocument)(this)),t=this.getDialogElement();t&&t!==e&&!(0,g.contains)(t,e)&&t.focus()}},getDialogElement:function(){var e=this.refs.modal;return e&&e.lastChild},isTopModal:function(){return b.isTopModal(this)}});_.manager=b,t["default"]=_},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){var n=-1;return e.some(function(e,r){return t(e,r)?(n=r,!0):void 0}),n}function a(e,t){return o(e,function(e){return-1!==e.modals.indexOf(t)})}Object.defineProperty(t,"__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}}(),u=n(178),s=n(162),l=n(177),c=function(){function e(){var t=arguments.length<=0||void 0===arguments[0]?!0:arguments[0];r(this,e),this.hideSiblingNodes=t,this.modals=[],this.containers=[],this.data=[]}return i(e,[{key:"add",value:function(e,t,n){var r=this.modals.indexOf(e),o=this.containers.indexOf(t);if(-1!==r)return r;if(r=this.modals.length,this.modals.push(e),-1!==o)return this.data[o].modals.push(e),r;var a={modals:[e],classes:n?n.split(/\s+/):[],style:{overflow:t.style.overflow,paddingRight:t.style.paddingRight}},i={overflow:"hidden"};return a.overflowing=(0,l.isOverflowing)(t),a.overflowing&&(i.paddingRight=parseInt((0,u.addStyle)(t,"paddingRight")||0,10)+(0,l.getScrollbarSize)()+"px"),(0,u.addStyle)(t,i),a.classes.forEach(s.addClass.bind(null,t)),this.containers.push(t),this.data.push(a),r}},{key:"remove",value:function(e){var t=this.modals.indexOf(e);if(-1!==t){var n=a(this.data,e),r=this.data[n],o=this.containers[n];r.modals.splice(r.modals.indexOf(e),1),this.modals.splice(t,1),0===r.modals.length&&(Object.keys(r.style).forEach(function(e){return o.style[e]=r.style[e]}),r.classes.forEach(s.removeClass.bind(null,o)),this.containers.splice(n,1),this.data.splice(n,1))}}},{key:"isTopModal",value:function(e){return!!this.modals.length&&this.modals[this.modals.length-1]===e}}]),e}();t["default"]=c},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{ "default":e}}function o(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=n(159),s=r(u),l=n(2),c=r(l),p=n(160),d=r(p),f=c["default"].createClass({displayName:"ModalDialog",mixins:[d["default"]],propTypes:{dialogClassName:c["default"].PropTypes.string},render:function(){var e=this.props,t=e.className,n=e.style,r=a(e,["className","style"]),u=i({display:"block"},n),l=(0,s["default"])("modal",t),p=s["default"].apply(void 0,[this.prefix("dialog"),this.props.dialogClassName].concat(o(this.getClassNames())));return c["default"].createElement("div",i({title:null,tabIndex:"-1",role:"dialog",style:u,className:l},r),c["default"].createElement("div",{className:p},c["default"].createElement("div",{className:this.prefix("content"),role:"document"},this.props.children)))}});t["default"]=f},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(159),i=r(a),u=n(2),s=r(u),l=n(160),c=r(l),p=s["default"].createClass({displayName:"ModalBody",mixins:[c["default"]],getDefaultProps:function(){return{classPrefix:"modal"}},render:function(){var e=(0,i["default"])(this.prefix("body"),this.props.className);return s["default"].createElement("div",o({},this.props,{className:e}),this.props.children)}});t["default"]=p},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(159),i=r(a),u=n(2),s=r(u),l=n(170),c=r(l),p=n(160),d=r(p),f=s["default"].createClass({displayName:"ModalHeader",mixins:[d["default"]],contextTypes:{onModalHide:s["default"].PropTypes.func},propTypes:{closeButton:s["default"].PropTypes.bool,onHide:s["default"].PropTypes.func},getDefaultProps:function(){return{classPrefix:"modal",closeButton:!0}},render:function(){var e=(0,c["default"])(this.context.onModalHide,this.props.onHide),t=(0,i["default"])(this.prefix("header"),this.props.className),n=s["default"].createElement("button",{type:"button",className:"close","aria-label":"Close",onClick:e},s["default"].createElement("span",{"aria-hidden":"true"},"×"));return s["default"].createElement("div",o({},this.props,{className:t}),this.props.closeButton&&n,this.props.children)}});t["default"]=f},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(2),i=r(a),u=n(159),s=r(u),l=n(160),c=r(l),p=i["default"].createClass({displayName:"ModalTitle",mixins:[c["default"]],render:function(){var e=(0,s["default"])(this.prefix("title"),this.props.className);return i["default"].createElement("h4",o({},this.props,{className:e}),this.props.children)}});t["default"]=p},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(159),i=r(a),u=n(2),s=r(u),l=n(160),c=r(l),p=s["default"].createClass({displayName:"ModalFooter",mixins:[c["default"]],getDefaultProps:function(){return{classPrefix:"modal"}},render:function(){var e=(0,i["default"])(this.prefix("footer"),this.props.className);return s["default"].createElement("div",o({},this.props,{className:e}),this.props.children)}});t["default"]=p},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=n(2),s=r(u),l=n(159),c=r(l),p=n(160),d=r(p),f=n(202),h=r(f),v=n(203),m=r(v),y=s["default"].createClass({displayName:"Nav",mixins:[d["default"]],propTypes:{tabs:s["default"].PropTypes.bool,pills:s["default"].PropTypes.bool,justified:s["default"].PropTypes.bool,stacked:s["default"].PropTypes.bool,onSelect:s["default"].PropTypes.func,pullRight:s["default"].PropTypes.bool,activeKey:s["default"].PropTypes.any},contextTypes:{navbar:s["default"].PropTypes.bool},getDefaultProps:function(){return{classPrefix:"nav",pullRight:!1}},render:function(){var e,t=this.props,n=t.tabs,r=t.pills,u=t.stacked,l=t.justified,p=t.pullRight,d=t.className,f=t.children,h=t.onSelect,v=t.activeKey,m=a(t,["tabs","pills","stacked","justified","pullRight","className","children","onSelect","activeKey"]),y=(0,c["default"])((e={nav:!0,"navbar-right":p,"navbar-nav":this.context.navbar},o(e,this.prefix("pills"),r),o(e,this.prefix("tabs"),n),o(e,this.prefix("stacked"),u),o(e,this.prefix("justified"),l),e),d),g=s["default"].Children.map(f,function(e,t){return s["default"].cloneElement(e,{key:t,onSelect:h,active:v&&v===e.props.eventKey||e.props.active},e.props.children)});return s["default"].createElement("ul",i({},m,{className:y}),g)}});y.Item=h["default"],y.Dropdown=m["default"],t["default"]=y},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var 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},i=n(159),u=r(i),s=n(2),l=r(s),c=n(164),p=r(c),d=n(170),f=r(d),h=n(163),v=r(h),m=l["default"].createClass({displayName:"NavItem",propTypes:{active:l["default"].PropTypes.bool,disabled:l["default"].PropTypes.bool,href:l["default"].PropTypes.string,onClick:l["default"].PropTypes.func,onSelect:l["default"].PropTypes.func,eventKey:l["default"].PropTypes.any,componentClass:p["default"]},getDefaultProps:function(){return{href:"",active:!1,disabled:!1}},handleClick:function(e){this.props.onSelect&&(e.preventDefault(),this.props.disabled||this.props.onSelect(this.props.eventKey,e))},render:function(){var e=this.props,t=e.active,n=e.disabled,r=e.role,i=e.href,s=e.onClick,c=e.className,p=e.style,d=(e.onSelect,e.eventKey,e.children),h=o(e,["active","disabled","role","href","onClick","className","style","onSelect","eventKey","children"]),m=(0,u["default"])({active:t,disabled:n},c),y=this.props.componentClass||v["default"];return l["default"].createElement("li",{role:"presentation",className:m,style:p},l["default"].createElement(y,a({},h,{disabled:n,role:r,href:i,onClick:(0,f["default"])(s,this.handleClick)}),d))}});t["default"]=m},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(2),i=r(a),u=n(159),s=r(u),l=n(168),c=r(l),p=i["default"].createClass({displayName:"NavDropdown",render:function(){var e=(0,s["default"])({"nav-dropdown":!0});return i["default"].createElement(c["default"],o({},this.props,{componentClass:"li",useAnchor:!0,className:e}),this.props.children)}});t["default"]=p},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=n(2),s=r(u),l=n(159),c=r(l),p=n(160),d=r(p),f=n(164),h=r(f),v=n(205),m=r(v),y=n(206),g=r(y),b=n(208),_=r(b),E=n(209),N=r(E),O=s["default"].createClass({displayName:"Navbar",mixins:[d["default"]],propTypes:{classPrefix:s["default"].PropTypes.string,fixedTop:s["default"].PropTypes.bool,fixedBottom:s["default"].PropTypes.bool,inverse:s["default"].PropTypes.bool,componentClass:h["default"],onToggle:s["default"].PropTypes.func},childContextTypes:{classPrefix:s["default"].PropTypes.string,navbar:s["default"].PropTypes.bool,expanded:s["default"].PropTypes.bool,onToggle:s["default"].PropTypes.func},getDefaultProps:function(){return{classPrefix:"navbar",componentClass:"div",inverse:!1}},getInitialState:function(){return{expanded:!1}},getChildContext:function(){return{navbar:!0,classPrefix:this.props.classPrefix,onToggle:this.handleToggle,expanded:this.state.expanded}},handleToggle:function(){var e=!this.state.expanded;this.setState({expanded:e}),this.props.onToggle&&this.props.onToggle()},render:function(){var e,t=this.props,n=t.inverse,r=t.fixedTop,u=t.fixedBottom,l=t.componentClass,p=t.children,d=t.className,f=a(t,["inverse","fixedTop","fixedBottom","componentClass","children","className"]),h=(0,c["default"])(d,(e={navbar:!0},o(e,this.prefix("default"),!n),o(e,this.prefix("inverse"),n),o(e,this.prefix("fixed-top"),r),o(e,this.prefix("fixed-Bottom"),u),e));return s["default"].createElement(l,i({},f,{className:h,role:"navigation"}),p)}});O.Brand=m["default"],O.Header=_["default"],O.Collapse=g["default"],O.Toggle=N["default"],t["default"]=O},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var 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},i=n(2),u=r(i),s=n(159),l=r(s),c=u["default"].createClass({displayName:"NavbarBrand",render:function(){var e=this.props,t=e.className,n=e.children,r=o(e,["className","children"]),i=(0,l["default"])({"navbar-brand":!0},t);return u["default"].isValidElement(n)?u["default"].cloneElement(n,{className:(0,l["default"])(n.props.className,i)}):u["default"].createElement("span",a({},r,{className:i}),n)}});t["default"]=c},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var 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},i=n(2),u=r(i),s=n(159),l=r(s),c=n(207),p=r(c),d=u["default"].createClass({displayName:"NavbarCollapse",contextTypes:{expanded:u["default"].PropTypes.bool},render:function(){var e=this.props,t=e.children,n=o(e,["children"]),r=(0,l["default"])({collapse:!0,"navbar-collapse":!0}),i=this.context.expanded;return u["default"].createElement(p["default"],a({"in":i},n),u["default"].createElement("div",{className:r},t))}});t["default"]=d},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function 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 i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function u(e,t){var n=t["offset"+b(e)],r=E[e];return n+parseInt((0,c.getStyle)(t,r[0]),10)+parseInt((0,c.getStyle)(t,r[1]),10)}Object.defineProperty(t,"__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},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}}(),c=n(178),p=n(2),d=r(p),f=n(159),h=r(f),v=n(186),m=r(v),y=n(170),g=r(y),b=function(e){return e[0].toUpperCase()+e.substr(1)},_=function(e){return e.offsetHeight},E={height:["marginTop","marginBottom"],width:["marginLeft","marginRight"]},N=function(e){function t(e,n){o(this,t);var r=a(this,Object.getPrototypeOf(t).call(this,e,n));return r.onEnterListener=r.handleEnter.bind(r),r.onEnteringListener=r.handleEntering.bind(r),r.onEnteredListener=r.handleEntered.bind(r),r.onExitListener=r.handleExit.bind(r),r.onExitingListener=r.handleExiting.bind(r),r}return i(t,e),l(t,[{key:"render",value:function(){var e=(0,g["default"])(this.onEnterListener,this.props.onEnter),t=(0,g["default"])(this.onEnteringListener,this.props.onEntering),n=(0,g["default"])(this.onEnteredListener,this.props.onEntered),r=(0,g["default"])(this.onExitListener,this.props.onExit),o=(0,g["default"])(this.onExitingListener,this.props.onExiting);return d["default"].createElement(m["default"],s({ref:"transition"},this.props,{"aria-expanded":this.props.role?this.props["in"]:null,className:(0,h["default"])(this.props.className,{width:"width"===this._dimension()}),exitedClassName:"collapse",exitingClassName:"collapsing",enteredClassName:"collapse in",enteringClassName:"collapsing",onEnter:e,onEntering:t,onEntered:n,onExit:r,onExiting:o,onExited:this.props.onExited}),this.props.children)}},{key:"handleEnter",value:function(e){var t=this._dimension();e.style[t]="0"}},{key:"handleEntering",value:function(e){var t=this._dimension();e.style[t]=this._getScrollDimensionValue(e,t)}},{key:"handleEntered",value:function(e){var t=this._dimension();e.style[t]=null}},{key:"handleExit",value:function(e){var t=this._dimension();e.style[t]=this.props.getDimensionValue(t,e)+"px"}},{key:"handleExiting",value:function(e){var t=this._dimension();_(e),e.style[t]="0"}},{key:"_dimension",value:function(){return"function"==typeof this.props.dimension?this.props.dimension():this.props.dimension}},{key:"_getTransitionInstance",value:function(){return this.refs.transition}},{key:"_getScrollDimensionValue",value:function(e,t){return e["scroll"+b(t)]+"px"}}]),t}(d["default"].Component);N.propTypes={"in":d["default"].PropTypes.bool,unmountOnExit:d["default"].PropTypes.bool,transitionAppear:d["default"].PropTypes.bool,timeout:d["default"].PropTypes.number,onEnter:d["default"].PropTypes.func,onEntering:d["default"].PropTypes.func,onEntered:d["default"].PropTypes.func,onExit:d["default"].PropTypes.func,onExiting:d["default"].PropTypes.func,onExited:d["default"].PropTypes.func,dimension:d["default"].PropTypes.oneOfType([d["default"].PropTypes.oneOf(["height","width"]),d["default"].PropTypes.func]),getDimensionValue:d["default"].PropTypes.func,role:d["default"].PropTypes.string},N.defaultProps={"in":!1,timeout:300,unmountOnExit:!1,transitionAppear:!1,dimension:"height",getDimensionValue:u},t["default"]=N},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var 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},i=n(2),u=r(i),s=n(159),l=r(s),c=u["default"].createClass({displayName:"NavbarHeader",render:function(){var e=this.props,t=e.className,n=o(e,["className"]),r=(0,l["default"])({"navbar-header":!0},t);return u["default"].createElement("div",a({},n,{className:r}))}});t["default"]=c},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var 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},i=n(159),u=r(i),s=n(2),l=r(s),c=n(170),p=r(c),d=l["default"].createClass({displayName:"NavbarToggle",propTypes:{onClick:l["default"].PropTypes.func,children:l["default"].PropTypes.node},contextTypes:{onToggle:l["default"].PropTypes.func,expanded:l["default"].PropTypes.bool},render:function(){var e=this.props,t=e.onClick,n=e.className,r=e.children,i=o(e,["onClick","className","children"]),s=this.context,c=s.onToggle,d=s.expanded,f=a({},i,{type:"button",onClick:(0,p["default"])(t,c),className:(0,u["default"])("navbar-toggle",!d&&"collapsed",n)});return r?l["default"].createElement("button",f,r):l["default"].createElement("button",f,l["default"].createElement("span",{className:"sr-only"},"Toggle navigation"),l["default"].createElement("span",{className:"icon-bar"}),l["default"].createElement("span",{className:"icon-bar"}),l["default"].createElement("span",{className:"icon-bar"}))}});t["default"]=d},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var 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},i=n(2),u=r(i),s=n(159),l=r(s),c=n(211),p=r(c),d=u["default"].createClass({displayName:"Breadcrumb",render:function(){var e=this.props,t=e.className,n=e.children,r=o(e,["className","children"]);return u["default"].createElement("ol",a({},r,{role:"navigation","aria-label":"breadcrumbs",className:(0,l["default"])(t,"breadcrumb")}),n)}});d.Item=p["default"],t["default"]=d},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var 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},i=n(159),u=r(i),s=n(2),l=r(s),c=n(163),p=r(c),d=l["default"].createClass({displayName:"BreadcrumbItem",propTypes:{active:l["default"].PropTypes.bool,id:l["default"].PropTypes.oneOfType([l["default"].PropTypes.string,l["default"].PropTypes.number]),linkId:l["default"].PropTypes.oneOfType([l["default"].PropTypes.string,l["default"].PropTypes.number]),href:l["default"].PropTypes.string,title:l["default"].PropTypes.node,target:l["default"].PropTypes.string},getDefaultProps:function(){return{active:!1}},renderItem:function(e,t){return this.props.active?l["default"].createElement("span",e," ",this.props.children," "):l["default"].createElement(p["default"],a({},e,t),this.props.children)},render:function(){var e=this.props,t=e.active,n=e.className,r=e.id;e.linkId,e.children,e.href,e.title,e.target,o(e,["active","className","id","linkId","children","href","title","target"]);return l["default"].createElement("li",{id:r,className:(0,u["default"])(n,{active:t})},this.renderItem())}});t["default"]=d},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=n(159),s=r(u),l=n(2),c=r(l),p=n(164),d=r(p),f=n(160),h=r(f),v=n(213),m=r(v),y=n(163),g=r(y),b=c["default"].createClass({displayName:"Pagination",mixins:[h["default"]],propTypes:{activePage:c["default"].PropTypes.number,pages:c["default"].PropTypes.number,maxButtons:c["default"].PropTypes.number,boundaryLinks:c["default"].PropTypes.bool,ellipsis:c["default"].PropTypes.oneOfType([c["default"].PropTypes.bool,c["default"].PropTypes.node]),first:c["default"].PropTypes.oneOfType([c["default"].PropTypes.bool,c["default"].PropTypes.node]),last:c["default"].PropTypes.oneOfType([c["default"].PropTypes.bool,c["default"].PropTypes.node]),prev:c["default"].PropTypes.oneOfType([c["default"].PropTypes.bool,c["default"].PropTypes.node]),next:c["default"].PropTypes.oneOfType([c["default"].PropTypes.bool,c["default"].PropTypes.node]),onSelect:c["default"].PropTypes.func,buttonComponentClass:d["default"],classPrefix:c["default"].PropTypes.string},getDefaultProps:function(){return{activePage:1,pages:1,maxButtons:0,first:!1,last:!1,prev:!1,next:!1,ellipsis:!1,boundaryLinks:!1,classPrefix:"pagination",buttonComponentClass:g["default"]}},renderPageButtons:function(){var e=[],t=void 0,n=void 0,r=void 0,o=this.props,a=o.maxButtons,i=o.activePage,u=o.pages,s=o.ellipsis,l=o.boundaryLinks;if(a){var p=i-parseInt(a/2,10);t=p>1?p:1,r=u>=t+a,r?n=t+a-1:(n=u,t=u-a+1,1>t&&(t=1))}else t=1,n=u;for(var d=t;n>=d;d++)e.push(this.renderItem({key:d,eventKey:d,active:d===i,children:d}));return l&&s&&1!==t&&(e.unshift(this.renderItem({key:"ellipsisFirst",disabled:!0,children:c["default"].createElement("span",{"aria-label":"More"},s===!0?"…":s)})),e.unshift(this.renderItem({key:1,eventKey:1,children:1}))),a&&r&&s&&(e.push(this.renderItem({key:"ellipsis",disabled:!0,children:c["default"].createElement("span",{"aria-label":"More"},s===!0?"…":s)})),l&&n!==u&&e.push(this.renderItem({key:u,eventKey:u,disabled:!1,children:u}))),e},renderPrev:function(){var e=this.props,t=(e.pages,e.activePage),n=e.prev;return this.props.prev?this.renderItem({key:"prev",eventKey:t-1,disabled:1===t,children:c["default"].createElement("span",{"aria-label":"Previous"},n===!0?"›":n)}):null},renderNext:function(){var e=this.props,t=e.pages,n=e.activePage,r=e.next;return this.props.next?this.renderItem({key:"next",eventKey:n+1,disabled:n>=t,children:c["default"].createElement("span",{"aria-label":"Next"},r===!0?"›":r)}):null},renderFirst:function(){var e=this.props,t=(e.pages,e.activePage),n=e.first;return n?this.renderItem({key:"first",eventKey:1,disabled:1===t,children:c["default"].createElement("span",{"aria-label":"First"},n===!0?"«":n)}):null},renderLast:function(){var e=this.props,t=e.pages,n=e.activePage,r=e.last;return r?this.renderItem({key:"last",eventKey:t,disabled:n>=t,children:c["default"].createElement("span",{"aria-label":"Last"},r===!0?"»":r)}):null},renderItem:function(e){var t=e.children,n=a(e,["children"]);return n.disabled||(n.onSelect=this.props.onSelect),c["default"].createElement(m["default"],i({},n,{componentClass:this.props.buttonComponentClass}),t)},render:function(){var e=s["default"].apply(void 0,[{pagination:!0}].concat(o(this.getClassNames()),[this.props.className]));return c["default"].createElement("ul",i({},this.props,{className:e}),this.renderFirst(),this.renderPrev(),this.renderPageButtons(),this.renderNext(),this.renderLast())}});t["default"]=b},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__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},i=n(159),u=r(i),s=n(2),l=r(s),c=n(164),p=r(c),d=n(170),f=r(d),h=l["default"].createClass({displayName:"PaginationButton",propTypes:{className:l["default"].PropTypes.string,eventKey:l["default"].PropTypes.any,onSelect:l["default"].PropTypes.func,disabled:l["default"].PropTypes.bool,active:l["default"].PropTypes.bool,onClick:l["default"].PropTypes.func,componentClass:p["default"]},getDefaultProps:function(){return{active:!1,disabled:!1}},handleClick:function(e){this.props.disabled||this.props.onSelect&&this.props.onSelect(this.props.eventKey,e)},render:function(){var e=this.props,t=e.active,n=e.disabled,r=e.onClick,i=e.componentClass,s=e.className,c=e.style,p=(e.onSelect,o(e,["active","disabled","onClick","componentClass","className","style","onSelect"]));return l["default"].createElement("li",{className:(0,u["default"])(s,{active:t,disabled:n}),style:c},l["default"].createElement(i,a({},p,{disabled:n,onClick:(0,f["default"])(r,this.handleClick)})))}});t["default"]=h},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=n(159),s=r(u),l=n(2),c=r(l),p=n(164),d=r(p),f=n(160),h=r(f),v=c["default"].createClass({displayName:"Form",mixins:[h["default"]],propTypes:{horizontal:c["default"].PropTypes.bool,inline:c["default"].PropTypes.bool,classPrefix:c["default"].PropTypes.string,componentClass:d["default"]},getDefaultProps:function(){return{classPrefix:"form",horizontal:!1,inline:!1,componentClass:"form"}},render:function(){var e,t=this.props,n=t.horizontal,r=t.inline,u=t.componentClass,l=t.className,p=a(t,["horizontal","inline","componentClass","className"]),d=(0,s["default"])((e={form:!0},o(e,this.prefix("horizontal"),n),o(e,this.prefix("inline"),r),e),l);return c["default"].createElement(u,i({},p,{className:d}))}});t["default"]=v},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=n(159),s=r(u),l=n(2),c=r(l),p=c["default"].createClass({displayName:"FormGroup",propTypes:{controlId:c["default"].PropTypes.string,validationState:c["default"].PropTypes.oneOf(["success","warning","error"])},childContextTypes:{formGroup:c["default"].PropTypes.object.isRequired},getChildContext:function(){var e=this.props,t=e.controlId,n=e.validationState;e.children;return{formGroup:{controlId:t,validationState:n}}},render:function(){var e=this.props,t=e.validationState,n=e.className,r=e.children,u=(e.controlId,a(e,["validationState","className","children","controlId"])),l=(0,s["default"])(o({"form-group":!0},"has-"+t,t&&!0),n);return c["default"].createElement("div",i({},u,{className:l}),r)}});t["default"]=p},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var 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},i=n(2),u=r(i),s=n(159),l=r(s),c=u["default"].createClass({displayName:"ControlLabel",propTypes:{htmlFor:u["default"].PropTypes.string,srOnly:u["default"].PropTypes.bool},contextTypes:{formGroup:u["default"].PropTypes.object},getDefaultProps:function(){return{srOnly:!1}},render:function(){var e=this.context.formGroup,t=e&&e.controlId,n=this.props,r=n.htmlFor,i=void 0===r?t:r,s=n.srOnly,c=n.className,p=o(n,["htmlFor","srOnly","className"]);if(null===i)throw new Error("`controlId` is ignored on `<ControlLabel>` when `htmlFor` is specified.");var d=(0,l["default"])({"control-label":!0,"sr-only":s},c);return u["default"].createElement("label",a({},p,{htmlFor:i,className:d}))}});t["default"]=c},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var 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},i=n(159),u=r(i),s=n(2),l=r(s),c=n(164),p=r(c),d=n(160),f=r(d),h=l["default"].createClass({displayName:"FormControl",mixins:[f["default"]],propTypes:{componentClass:p["default"],type:l["default"].PropTypes.string,id:l["default"].PropTypes.string},contextTypes:{formGroup:l["default"].PropTypes.object},getDefaultProps:function(){return{componentClass:"input"}},render:function(){var e=this.context.formGroup,t=e&&e.controlId,n=this.props,r=n.componentClass,i=n.type,s=n.id,c=void 0===s?t:s,p=n.className,d=o(n,["componentClass","type","id","className"]);if(null===c)throw new Error("`controlId` is ignored on `<FormControl>` when `id` is specified.");var f=(0,u["default"])({"form-control":"file"!==i},p);return l["default"].createElement(r,a({},d,{type:i,id:c,className:f}))}});t["default"]=h},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var 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},i=n(2),u=r(i),s=n(159),l=r(s),c=u["default"].createClass({displayName:"HelpBlock",propTypes:{htmlFor:u["default"].PropTypes.string},contextTypes:{formGroup:u["default"].PropTypes.object},render:function(){var e=this.context.formGroup,t=e&&e.controlId,n=this.props,r=n.className,i=n.htmlFor,s=void 0===i?t:i,c=o(n,["className","htmlFor"]),p=(0,l["default"])({"help-block":!0},r);return u["default"].createElement("span",a({},c,{htmlFor:s,className:p}))}});t["default"]=c},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var a=n(159),i=r(a),u=n(2),s=r(u),l=n(170),c=r(l),p=s["default"].createClass({displayName:"Checkbox",propTypes:{id:s["default"].PropTypes.string,name:s["default"].PropTypes.string,inline:s["default"].PropTypes.bool,title:s["default"].PropTypes.string,disabled:s["default"].PropTypes.bool,checked:s["default"].PropTypes.bool, onClick:s["default"].PropTypes.func,onChange:s["default"].PropTypes.func},contextTypes:{formGroup:s["default"].PropTypes.object},getDefaultProps:function(){return{inline:!1,disabled:!1}},getInitialState:function(){return{checked:this.props.checked}},handleChange:function(e){this.props.disabled||this.setState({checked:!this.state.checked})},render:function(){var e=this.props,t=(e.type,e.inline),n=e.title,r=e.name,a=e.disabled,u=e.className,l=e.children,p=e.onChange,d=(o(e,["type","inline","title","name","disabled","className","children","onChange"]),(0,i["default"])({"checkbox-inline":t},u)),f=(0,i["default"])({checker:!0,disabled:a}),h=s["default"].createElement("span",{className:(0,i["default"])({checked:this.state.checked})},s["default"].createElement("input",{type:"checkbox",name:r,disabled:a,onChange:(0,c["default"])(this.handleChange,p),defaultChecked:this.state.checked}));return s["default"].createElement("label",{className:d},s["default"].createElement("div",{className:f,role:"checkbox"},h),n||l)}});t["default"]=p},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(2),a=r(o),i=n(159),u=r(i),s=n(219),l=(r(s),a["default"].createClass({displayName:"CheckboxList",propTypes:{name:a["default"].PropTypes.string,inline:a["default"].PropTypes.bool},render:function(){var e=this.props,t=e.className,n=e.inline,r=e.name,o=e.children,i=(0,u["default"])({"checkbox-list":!0},t),s=a["default"].Children.map(o,function(e,t){return a["default"].cloneElement(e,{key:t,ref:"checkbox_"+t,inline:n,name:r},e.props.children)});return a["default"].createElement("div",{className:i,role:"checkbox-list"},s)}}));t["default"]=l},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var 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},i=n(159),u=r(i),s=n(2),l=r(s),c=n(170),p=r(c),d=l["default"].createClass({displayName:"Radio",propTypes:{id:l["default"].PropTypes.string,name:l["default"].PropTypes.string,inline:l["default"].PropTypes.bool,title:l["default"].PropTypes.string,disabled:l["default"].PropTypes.bool,checked:l["default"].PropTypes.bool,onClick:l["default"].PropTypes.func,onChange:l["default"].PropTypes.func},contextTypes:{formGroup:l["default"].PropTypes.object},getDefaultProps:function(){return{inline:!1,disabled:!1}},getInitialState:function(){return{checked:this.props.checked}},handleChange:function(e){this.setState({checked:e.target.checked})},render:function(){var e=this.props,t=(e.type,e.inline),n=e.title,r=e.name,i=e.className,s=e.children,c=(e.onClick,e.onChange),d=e.disabled,f=o(e,["type","inline","title","name","className","children","onClick","onChange","disabled"]),h=(0,u["default"])({"radio-inline":t},i),v=(0,u["default"])({radio:!0,disabled:d}),m=l["default"].createElement("span",{className:(0,u["default"])({checked:this.state.checked})},l["default"].createElement("input",a({},f,{type:"radio",name:r,disabled:d,onChange:(0,p["default"])(this.handleChange,c)})));return l["default"].createElement("label",{className:h},l["default"].createElement("div",{className:v,role:"radio"},m),n||s)}});t["default"]=d},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(2),a=r(o),i=n(161),u=r(i),s=n(159),l=r(s),c=n(221),p=(r(c),a["default"].createClass({displayName:"RadioList",propTypes:{options:a["default"].PropTypes.array,name:a["default"].PropTypes.string,inline:a["default"].PropTypes.bool},handleChange:function(e){if("radio"===e.target.type){var t=(this.props.children,e.target),n=this.refs;for(var r in n){var o=u["default"].findDOMNode(n[r]);t!==o&&n[r].setState({checked:!1})}}},render:function(){var e=this.props,t=e.className,n=e.inline,r=e.name,o=e.children,i=(e.options,(0,l["default"])({"radio-list":!0},t)),u=a["default"].Children.map(o,function(e,t){return a["default"].cloneElement(e,{key:t,ref:"radio_"+t,inline:n,name:r},e.props.children)});return a["default"].createElement("div",{onClick:this.handleChange,className:i,role:"radio-list"},u)}}));t["default"]=p},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=n(2),s=r(u),l=n(159),c=r(l),p=n(164),d=r(p),f=["default","muted","primary","success","warning","danger","info"],h=s["default"].createClass({displayName:"Text",propTypes:{bg:s["default"].PropTypes.bool,shape:s["default"].PropTypes.oneOf(f),componentClass:d["default"]},getDefaultProps:function(){return{shape:"default",componentClass:"p"}},render:function(){var e=this.props,t=e.componentClass,n=e.bg,r=e.shape,u=e.className,l=a(e,["componentClass","bg","shape","className"]),p=(0,c["default"])(o({},(n?"bg":"text")+"-"+r,!0),u);return s["default"].createElement(t,i({},l,{className:p}))}});t["default"]=h},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var 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},i=n(2),u=r(i),s=n(159),l=r(s),c=n(204),p=r(c),d=u["default"].createClass({displayName:"Header",render:function(){var e=this.props,t=e.children,n=e.className,r=o(e,["children","className"]),i=(0,l["default"])({header:!0},n);return u["default"].createElement(p["default"],a({},r,{className:i,fixedTop:!0,role:"header"}),u["default"].createElement("div",{className:"header-inner"},t))}});t["default"]=d},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=n(2),s=r(u),l=n(159),c=r(l),p=s["default"].createClass({displayName:"Sidebar",propTypes:{pullRight:s["default"].PropTypes.bool},contextTypes:{page:s["default"].PropTypes.bool},render:function(){var e=this.props,t=e.className,n=e.pullRight,r=a(e,["className","pullRight"]),u=this.context.page?"page-sidebar":"sidebar",l=u+"-wrapper",p=(0,c["default"])(o({collapse:!0,"navbar-collapse":!0,right:n},u,!0),t);return s["default"].createElement("div",i({},r,{className:l}),s["default"].createElement("div",{className:p},this.props.children))}});t["default"]=p},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=n(2),s=r(u),l=n(159),c=r(l),p=n(164),d=r(p),f=s["default"].createClass({displayName:"Grid",propTypes:{fluid:s["default"].PropTypes.bool,componentClass:d["default"]},getDefaultProps:function(){return{componentClass:"div",fluid:!1}},render:function(){var e=this.props,t=e.componentClass,n=e.fluid,r=e.className,u=e.children,l=a(e,["componentClass","fluid","className","children"]),p=(0,c["default"])(o({},"container"+(n?"-fluid":""),!0),r);return s["default"].createElement(t,i({},l,{className:p}),u)}});t["default"]=f},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var 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},i=n(2),u=r(i),s=n(159),l=r(s),c=n(164),p=r(c),d=u["default"].createClass({displayName:"Row",propTypes:{componentClass:p["default"]},getDefaultProps:function(){return{componentClass:"div"}},render:function(){var e=this.props,t=e.componentClass,n=e.className,r=e.children,i=o(e,["componentClass","className","children"]),s=(0,l["default"])(n,"row");return u["default"].createElement(t,a({},i,{className:s}),r)}});t["default"]=d},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(2),i=r(a),u=n(159),s=r(u),l=n(164),c=r(l),p=["xs","sm","md","lg"],d=[1,2,3,4,5,6,7,8,9,10,11,12],f=i["default"].createClass({displayName:"Col",propTypes:{xs:i["default"].PropTypes.oneOf(d),sm:i["default"].PropTypes.oneOf(d),md:i["default"].PropTypes.oneOf(d),lg:i["default"].PropTypes.oneOf(d),xsOffset:i["default"].PropTypes.oneOf(d),smOffset:i["default"].PropTypes.oneOf(d),mdOffset:i["default"].PropTypes.oneOf(d),lgOffset:i["default"].PropTypes.oneOf(d),xsPush:i["default"].PropTypes.oneOf(d),smPush:i["default"].PropTypes.oneOf(d),mdPush:i["default"].PropTypes.oneOf(d),lgPush:i["default"].PropTypes.oneOf(d),xsPull:i["default"].PropTypes.oneOf(d),smPull:i["default"].PropTypes.oneOf(d),mdPull:i["default"].PropTypes.oneOf(d),lgPull:i["default"].PropTypes.oneOf(d),xsHidden:i["default"].PropTypes.bool,smHidden:i["default"].PropTypes.bool,mdHidden:i["default"].PropTypes.bool,lgHidden:i["default"].PropTypes.bool,componentClass:c["default"]},getDefaultProps:function(){return{componentClass:"div"}},render:function(){var e=this,t=this.props.componentClass,n={};return p.map(function(t){var r=e.props[t+"Offset"],o=e.props[t+"Push"],a=e.props[t+"Pull"];n["hidden-"+t]=e.props[t+"Hidden"],n["col-"+t+"-"+e.props[t]]=e.props[t]>0,n["col-"+t+"-offset-"+r]=r>=0,n["col-"+t+"-push-"+o]=o>=0,n["col-"+t+"-pull-"+a]=a>=0}),i["default"].createElement(t,o({},this.props,{className:(0,s["default"])(this.props.className,n)}),this.props.children)}});t["default"]=f},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var 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},i=n(2),u=r(i),s=n(159),l=r(s),c=u["default"].createClass({displayName:"Table",propTypes:{striped:u["default"].PropTypes.bool,bordered:u["default"].PropTypes.bool,condensed:u["default"].PropTypes.bool,hover:u["default"].PropTypes.bool,responsive:u["default"].PropTypes.bool},getDefaultProps:function(){return{bordered:!1,condensed:!1,hover:!1,responsive:!1,striped:!1}},render:function(){var e=this.props,t=e.striped,n=e.bordered,r=e.condensed,i=e.hover,s=e.children,c=e.className,p=o(e,["striped","bordered","condensed","hover","children","className"]),d=(0,l["default"])({table:!0,"table-striped":t,"table-bordered":n,"table-condensed":r,"table-hover":i},c),f=u["default"].createElement("table",a({},p,{className:d}),s);return this.props.responsive?u["default"].createElement("div",{className:"table-responsive"},f):f}});t["default"]=c},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var 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},i=n(2),u=r(i),s=n(159),l=r(s),c=u["default"].createClass({displayName:"Container",propTypes:{page:u["default"].PropTypes.bool},childContextTypes:{page:u["default"].PropTypes.bool},getChildContext:function(){return{page:!0}},render:function(){var e=this.props,t=e.className,n=e.page,r=o(e,["className","page"]),i=n?"page-container":"container",s=(0,l["default"])(i,t);return u["default"].createElement("div",a({},r,{className:s}))}});t["default"]=c},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var 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},i=n(2),u=r(i),s=n(159),l=r(s),c=u["default"].createClass({displayName:"Content",contextTypes:{page:u["default"].PropTypes.bool},render:function(){var e=this.props,t=e.className,n=o(e,["className"]),r=this.context.page?"page-content":"content",i=r+"-wrapper",s=(0,l["default"])(r,t);return u["default"].createElement("div",a({},n,{className:i}),u["default"].createElement("div",{className:s},this.props.children))}});t["default"]=c},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=n(2),s=r(u),l=n(159),c=r(l),p=n(207),d=r(p),f=n(160),h=r(f),v=s["default"].createClass({displayName:"Panel",mixins:[h["default"]],propTypes:{collapsible:s["default"].PropTypes.bool,header:s["default"].PropTypes.node,id:s["default"].PropTypes.oneOfType([s["default"].PropTypes.string,s["default"].PropTypes.number]),defaultExpanded:s["default"].PropTypes.bool,expanded:s["default"].PropTypes.bool,eventKey:s["default"].PropTypes.any,headerRole:s["default"].PropTypes.string,panelRole:s["default"].PropTypes.string,classPrefix:s["default"].PropTypes.string,onSelect:s["default"].PropTypes.func,onEnter:d["default"].propTypes.onEnter,onEntering:d["default"].propTypes.onEntering,onEntered:d["default"].propTypes.onEntered,onExit:d["default"].propTypes.onExit,onExiting:d["default"].propTypes.onExiting,onExited:d["default"].propTypes.onExited},getDefaultProps:function(){return{defaultExpanded:!1,shape:"default",classPrefix:"panel"}},getInitialState:function(){return{expanded:this.props.defaultExpanded}},handleSelect:function(e){e.persist(),e.selected=!0,this.props.onSelect?this.props.onSelect(this.props.eventKey,e):e.preventDefault(),e.selected&&this.handleToggle()},handleToggle:function(){this.setState({expanded:!this.state.expanded})},isExpanded:function(){return null!==this.props.expanded?this.props.expanded:this.state.expanded},renderCollapsibleBody:function(e){var t={onEnter:this.props.onEnter,onEntering:this.props.onEntering,onEntered:this.props.onEntered,onExit:this.props.onExit,onExiting:this.props.onExiting,onExited:this.props.onExited,"in":this.isExpanded()},n={className:this.prefix("collapse"),id:this.props.id,ref:"panel","aria-hidden":!this.isExpanded()};return e&&(n.role=e),s["default"].createElement(d["default"],t,s["default"].createElement("div",n,this.renderBody()))},renderBody:function(){function e(){return{key:l.length}}function t(t){l.push((0,u.cloneElement)(t,e()))}function n(t){l.push(s["default"].createElement("div",i({className:p},e()),t))}function r(){0!==c.length&&(n(c),c=[])}var o=this,a=this.props.children,l=[],c=[],p=this.prefix("body");return Array.isArray(a)&&0!==a.length?(a.forEach(function(e){o.shouldRenderFill(e)?(r(),t(e)):c.push(e)}),r()):this.shouldRenderFill(a)?t(a):n(a),l},shouldRenderFill:function(e){return s["default"].isValidElement(e)&&null!==e.props.fill},renderHeading:function(e){var t=this.props.header;if(!t)return null;if(!s["default"].isValidElement(t)||Array.isArray(t))t=this.props.collapsible?this.renderCollapsibleTitle(t,e):t;else{var n=(0,c["default"])(this.prefix("title"),t.props.className);t=this.props.collapsible?(0,u.cloneElement)(t,{className:n,children:this.renderAnchor(t.props.children,e)}):(0,u.cloneElement)(t,{className:n})}return s["default"].createElement("div",{className:this.prefix("heading"),onClick:this.handleSelect},t)},renderAnchor:function(e,t){return s["default"].createElement("a",{href:"#"+(this.props.id||""),"aria-controls":this.props.collapsible?this.props.id:null,className:this.isExpanded()?null:"collapsed","aria-expanded":this.isExpanded(),"aria-selected":this.isExpanded(),role:t},e)},renderCollapsibleTitle:function(e,t){return s["default"].createElement("h4",{className:this.prefix("title"),role:"presentation"},this.renderAnchor(e,t))},render:function(){var e=this.props,t=e.headerRole,n=e.panelRole,r=e.className,u=e.collapsible,l=e.id,p=a(e,["headerRole","panelRole","className","collapsible","id"]),d=c["default"].apply(void 0,["panel",r].concat(o(this.getClassNames())));return s["default"].createElement("div",i({},p,{className:d,id:u?null:l,onSelect:null}),this.renderHeading(t),u?this.renderCollapsibleBody(n):this.renderBody())}});t["default"]=v},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var 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},i=n(159),u=r(i),s=n(2),l=r(s),c=l["default"].createClass({displayName:"PanelGroup",propTypes:{accordion:l["default"].PropTypes.bool,activeKey:l["default"].PropTypes.any,className:l["default"].PropTypes.string,children:l["default"].PropTypes.node,defaultActiveKey:l["default"].PropTypes.any,classPrefix:l["default"].PropTypes.string,onSelect:l["default"].PropTypes.func},getDefaultProps:function(){return{classPrefix:"panel-group",accordion:!1}},getInitialState:function(){return{activeKey:this.props.defaultActiveKey}},renderPanel:function(e,t){if(!l["default"].isValidElement(e))return e;var n=this.props.activeKey?this.props.activeKey:this.state.activeKey,r={bsStyle:e.props.bsStyle||this.props.bsStyle,key:e.key?e.key:t,ref:e.ref};return this.props.accordion&&(r.headerRole="tab",r.panelRole="tabpanel",r.collapsible=!0,r.expanded=e.props.eventKey===n,r.onSelect=this.handleSelect),(0,s.cloneElement)(e,r)},shouldComponentUpdate:function(){return!this._isChanging},handleSelect:function(e,t){t.preventDefault(),this.props.onSelect&&(this._isChanging=!0,this.props.onSelect(e,t),this._isChanging=!1),this.state.activeKey===e&&(e=null),this.setState({activeKey:e})},render:function(){var e=this.props,t=e.className,n=e.accordion,r=e.children,i=o(e,["className","accordion","children"]),s=(0,u["default"])("panel-group",t);return n&&(i.role="tablist"),l["default"].createElement("div",a({},i,{className:s,onSelect:null}),l["default"].Children.map(r,this.renderPanel))}});t["default"]=c}])});
app/js/components/content/PageComponent.js
lukemarsh/tab-hq-react
'use strict'; import React from 'react'; import TextComponent from './TextComponent'; import ListComponent from './ListComponent'; import ImageComponent from './ImageComponent'; import NewSectionComponent from './NewSectionComponent'; import Api from '../../utils/Api'; import ComponentStore from '../../stores/ComponentStore'; import ComponentActionCreators from '../../actions/ComponentActionCreators'; import ReorderMixin from '../../mixins/ReorderMixin'; import _ from 'lodash'; import Reflux from 'reflux'; require('../../../styles/PageComponent.sass'); function getStateFromStores(sectionId) { return { allComponents: ComponentStore.getAllBySectionId(sectionId) }; } const PageComponent = React.createClass({ mixins: [ReorderMixin, Reflux.listenTo(ComponentStore, '_onChange')], getInitialState() { return { allComponents: getStateFromStores(this.props.sectionId) }; }, setDraggableData(components) { ComponentActionCreators.updateComponents(components); }, _onChange() { this.setState(getStateFromStores(this.props.sectionId)); }, componentDidMount() { Api.getAllComponents(this.props.sectionId); }, componentWillUnmount() { ComponentStore.clearAllBySectionId(this.props.sectionId) }, render() { let template = this.props.template; let components = this.state.allComponents; let userIsAdmin = this.props.userIsAdmin; let sectionComponents = []; this.loadDraggableData(components); _.each(components, ((component) => { switch (component.componentType) { case 'TextComponent': sectionComponents.push(<TextComponent components={components} key={component.id} component={component} data={component.data} sectionId={this.props.sectionId} userIsAdmin={userIsAdmin} componentId={component.id} dragEnd={this.dragEnd} dragStart={this.dragStart} mouseDown={this.mouseDown}></TextComponent>); break; case 'ListComponent': sectionComponents.push(<ListComponent key={component.id} component={component} data={component.data} sectionId={this.props.sectionId} userIsAdmin={userIsAdmin} componentId={component.id} dragEnd={this.dragEnd} dragStart={this.dragStart} mouseDown={this.mouseDown}></ListComponent>); break; case 'ImageComponent': sectionComponents.push(<ImageComponent key={component.id} component={component} data={component.data} sectionId={this.props.sectionId} userIsAdmin={userIsAdmin} componentId={component.id} dragEnd={this.dragEnd} dragStart={this.dragStart} mouseDown={this.mouseDown}></ImageComponent>) break; } })); return ( <div> <div onDragOver={this.dragOver}> {sectionComponents} </div> <NewSectionComponent userIsAdmin={userIsAdmin} categoryId={this.props.categoryId} sectionId={this.props.sectionId} template={template}></NewSectionComponent> </div> ); } }); module.exports = PageComponent;
jspm_packages/npm/[email protected]/es6/Link.js
Imms/imms.github.io
/* */ "format cjs"; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _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; } import React from 'react'; import warning from './routerWarning'; import invariant from 'invariant'; import { routerShape } from './PropTypes'; var _React$PropTypes = React.PropTypes; var bool = _React$PropTypes.bool; var object = _React$PropTypes.object; var string = _React$PropTypes.string; var func = _React$PropTypes.func; var oneOfType = _React$PropTypes.oneOfType; function isLeftClickEvent(event) { return event.button === 0; } function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); } // TODO: De-duplicate against hasAnyProperties in createTransitionManager. function isEmptyObject(object) { for (var p in object) { if (Object.prototype.hasOwnProperty.call(object, p)) return false; }return true; } function createLocationDescriptor(to, _ref) { var query = _ref.query; var hash = _ref.hash; var state = _ref.state; if (query || hash || state) { return { pathname: to, query: query, hash: hash, state: state }; } return to; } /** * A <Link> is used to create an <a> element that links to a route. * When that route is active, the link gets the value of its * activeClassName prop. * * For example, assuming you have the following route: * * <Route path="/posts/:postID" component={Post} /> * * You could use the following component to link to that route: * * <Link to={`/posts/${post.id}`} /> * * Links may pass along location state and/or query string parameters * in the state/query props, respectively. * * <Link ... query={{ show: true }} state={{ the: 'state' }} /> */ var Link = React.createClass({ displayName: 'Link', contextTypes: { router: routerShape }, propTypes: { to: oneOfType([string, object]).isRequired, query: object, hash: string, state: object, activeStyle: object, activeClassName: string, onlyActiveOnIndex: bool.isRequired, onClick: func, target: string }, getDefaultProps: function getDefaultProps() { return { onlyActiveOnIndex: false, style: {} }; }, handleClick: function handleClick(event) { if (this.props.onClick) this.props.onClick(event); if (event.defaultPrevented) return; !this.context.router ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Link>s rendered outside of a router context cannot navigate.') : invariant(false) : void 0; if (isModifiedEvent(event) || !isLeftClickEvent(event)) return; // If target prop is set (e.g. to "_blank"), let browser handle link. /* istanbul ignore if: untestable with Karma */ if (this.props.target) return; event.preventDefault(); var _props = this.props; var to = _props.to; var query = _props.query; var hash = _props.hash; var state = _props.state; var location = createLocationDescriptor(to, { query: query, hash: hash, state: state }); this.context.router.push(location); }, render: function render() { var _props2 = this.props; var to = _props2.to; var query = _props2.query; var hash = _props2.hash; var state = _props2.state; var activeClassName = _props2.activeClassName; var activeStyle = _props2.activeStyle; var onlyActiveOnIndex = _props2.onlyActiveOnIndex; var props = _objectWithoutProperties(_props2, ['to', 'query', 'hash', 'state', 'activeClassName', 'activeStyle', 'onlyActiveOnIndex']); process.env.NODE_ENV !== 'production' ? warning(!(query || hash || state), 'the `query`, `hash`, and `state` props on `<Link>` are deprecated, use `<Link to={{ pathname, query, hash, state }}/>. http://tiny.cc/router-isActivedeprecated') : void 0; // Ignore if rendered outside the context of router, simplifies unit testing. var router = this.context.router; if (router) { var location = createLocationDescriptor(to, { query: query, hash: hash, state: state }); props.href = router.createHref(location); if (activeClassName || activeStyle != null && !isEmptyObject(activeStyle)) { if (router.isActive(location, onlyActiveOnIndex)) { if (activeClassName) { if (props.className) { props.className += ' ' + activeClassName; } else { props.className = activeClassName; } } if (activeStyle) props.style = _extends({}, props.style, activeStyle); } } } return React.createElement('a', _extends({}, props, { onClick: this.handleClick })); } }); export default Link;
src/components/common/help/QueryHelpDialog.js
mitmedialab/MediaCloud-Web-Tools
import PropTypes from 'prop-types'; import React from 'react'; import { FormattedHTMLMessage, injectIntl } from 'react-intl'; import SimpleDialog from '../SimpleDialog'; const localMessages = { invitation: { id: 'help.query.invitation', defaultMessage: 'Learn about writing search terms.' }, title: { id: 'help.query.title', defaultMessage: 'Writing Media Cloud Queries' }, content: { id: 'help.query.content', defaultMessage: ` <p>You can query Media Cloud with boolean searches that match stories, a lot like you might use Google. Here are some examples:</p> <ul><li>Boolean Connectors</li> <ul><li><code>OR</code></li> <ul><li> - cheese OR cheesy - using "OR" searches for stories that use either "cheese" or the word "cheesy," or stories that contain both words</li> <li> - Note: OR is the default connector. This means that unless you specifically put quotations around words or add an "AND" or "NOT" between them, the system will treat your search as though there is an OR.</li> </ul></ul> <ul><li><code>AND</code></li> <ul><li> - cheese AND blue - using "AND" lets you look for stories that include both the word "cheese" and the word "blue"</li> </ul></ul> <ul><li><code>NOT</code></li> <ul><li> - cheese NOT blue - using "NOT" lets you remove content you don't want; searching for stories that use the word "cheese" but don't have the word "blue" in them</li> </ul></ul></ul> <ul><li>Other Search Parameters</li> <ul><li><code>ASTERIX</code></li> <ul><li><code>chees*</code> - using an asterix searches for stories that use any word that starts with "chees" - including "cheese", "cheesy", or others</li> </ul></ul> <ul><li><code>QUOTATIONS</code></li> <ul><li> - "blue cheese" - putting a phrase in quotes lets you search for stories that use the exact phrase "blue cheese"</li> <li> - Please note that we do not support searching for different forms of a word (using an asterisk) inside of quotation marks</li> </ul></ul> <ul><li><code>SEARCHING IN ANOTHER LANGUAGE</code></li> <ul><li> - fromage AND language:fr - using the "language:" keyword lets you narrow in on a language; here searching for stories that use the word "fromage" and have been detected by our system as being written in French</li> <li> - Visit our <a href="https://mediacloud.org/support/languages">language</a> guide to learn more about the language we support and their codes</li> </ul></ul> <ul><li><code>PARENTHESES</code></li> <ul><li> - cheese AND (blue OR manchego OR goat OR cheddar) - using parentheses lets you author more complex queries; searching here for stories that have the word "cheese" and at least one other word describing what type it is</li> </ul></ul> <ul><li><code>PROXIMITY SEARCH</code></li> <ul><li> - "cheese blue" ~10 - enter your keywords in quotation marks and then include a tilde ~, followed by the number of words you want to limit your search to in terms of proximity. This will return stories in which cheese and blue are within 10 words of each other.</li> <li> - Please note that we do not support searching for different forms of a word (using an asterisk) in proximity search</li> </ul></ul></ul> <p><a href="https://mediacloud.org/support/query-guide" target=_blank>Read our guide to creating queries to learn more</a>.</p> ` }, }; const QueryHelpDialog = (props) => { const { trigger } = props; const { formatMessage } = props.intl; return ( <SimpleDialog trigger={trigger} title={formatMessage(localMessages.title)} > <div className="query-help-dialog-content"> <FormattedHTMLMessage {...localMessages.content} /> </div> </SimpleDialog> ); }; QueryHelpDialog.propTypes = { intl: PropTypes.object.isRequired, trigger: PropTypes.string.isRequired, }; export default injectIntl( QueryHelpDialog );
src/components/entry/__tests__/Entry.spec.js
bcongdon/EachDay
import React from 'react' import { shallow, mount } from 'enzyme' import toJson from 'enzyme-to-json' import { Entry } from '../Entry' import { Dropdown } from 'semantic-ui-react' jest.mock('universal-cookie') const openEntryModal = jest.fn() const deleteEntry = jest.fn() describe('entry component', () => { beforeEach(() => { jest.resetAllMocks() }) it('should render a basic entry correctly', () => { var dash = shallow( <Entry id={1} rating={5} date='2017-01-01' notes='Foo bar baz' openEntryModal={openEntryModal} deleteEntry={deleteEntry} /> ) expect(toJson(dash)).toMatchSnapshot() }) it('should render without notes', () => { var dash = shallow( <Entry id={1} rating={5} date='2017-01-01' openEntryModal={openEntryModal} deleteEntry={deleteEntry} /> ) expect(toJson(dash)).toMatchSnapshot() }) it('should render without a rating', () => { var dash = shallow( <Entry id={1} date='2017-01-01' notes='Foo bar baz' openEntryModal={openEntryModal} deleteEntry={deleteEntry} /> ) expect(toJson(dash)).toMatchSnapshot() }) it('should call openEntryModel on edit click', () => { var dash = mount( <Entry id={1} date='2017-01-01' notes='Foo bar baz' openEntryModal={openEntryModal} deleteEntry={deleteEntry} /> ) dash.find(Dropdown.Item).findWhere((n) => n.props().icon === 'delete').simulate('click') expect(deleteEntry).toBeCalled() }) it('should call deleteEntry on delete click', () => { var dash = mount( <Entry id={1} date='2017-01-01' notes='Foo bar baz' openEntryModal={openEntryModal} deleteEntry={deleteEntry} /> ) dash.find(Dropdown.Item).findWhere((n) => n.props().icon === 'edit').simulate('click') expect(openEntryModal).toBeCalled() }) })
src/components/CartButton.js
longyarnz/WelFurnish-E-Commerce
import React from 'react'; export default function CartButton(props) { return ( <button className="cart-button" onClick={props.onClick}> <span>VIEW CART <b>{props.number}</b></span> </button> ); }
ajax/libs/js-data/2.0.0-rc.1/js-data.js
holtkamp/cdnjs
/*! * js-data * @version 2.0.0-rc.1 - Homepage <http://www.js-data.io/> * @author Jason Dobry <[email protected]> * @copyright (c) 2014-2015 Jason Dobry * @license MIT <https://github.com/js-data/js-data/blob/master/LICENSE> * * @overview Robust framework-agnostic data store. */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define(factory); else if(typeof exports === 'object') exports["JSData"] = factory(); else root["JSData"] = factory(); })(this, function() { 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__) { var _datastoreIndex = __webpack_require__(1); var _utils = __webpack_require__(2); var _errors = __webpack_require__(3); /** * The library export. * - window.JSData * - require('js-data') * - define(['js-data', function (JSData) { ... }]); * - import JSData from 'js-data' */ module.exports = { DS: _datastoreIndex['default'], DSUtils: _utils['default'], DSErrors: _errors['default'], createStore: function createStore(options) { return new _datastoreIndex['default'](options); }, version: { full: '2.0.0-rc.1', major: parseInt('2', 10), minor: parseInt('0', 10), patch: parseInt('0', 10), alpha: true ? 'false' : false, beta: true ? 'false' : false } }; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 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; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } /* jshint eqeqeq:false */ var _utils = __webpack_require__(2); var _errors = __webpack_require__(3); var _sync_methodsIndex = __webpack_require__(4); var _async_methodsIndex = __webpack_require__(5); function lifecycleNoopCb(resource, attrs, cb) { cb(null, attrs); } function lifecycleNoop(resource, attrs) { return attrs; } function compare(_x, _x2, _x3, _x4) { var _again = true; _function: while (_again) { var orderBy = _x, index = _x2, a = _x3, b = _x4; def = cA = cB = undefined; _again = false; var def = orderBy[index]; var cA = _utils['default'].get(a, def[0]), cB = _utils['default'].get(b, def[0]); if (_utils['default']._s(cA)) { cA = _utils['default'].upperCase(cA); } if (_utils['default']._s(cB)) { cB = _utils['default'].upperCase(cB); } if (def[1] === 'DESC') { if (cB < cA) { return -1; } else if (cB > cA) { return 1; } else { if (index < orderBy.length - 1) { _x = orderBy; _x2 = index + 1; _x3 = a; _x4 = b; _again = true; continue _function; } else { return 0; } } } else { if (cA < cB) { return -1; } else if (cA > cB) { return 1; } else { if (index < orderBy.length - 1) { _x = orderBy; _x2 = index + 1; _x3 = a; _x4 = b; _again = true; continue _function; } else { return 0; } } } } } var Defaults = (function () { function Defaults() { _classCallCheck(this, Defaults); } _createClass(Defaults, [{ key: 'errorFn', value: function errorFn(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); } } }]); return Defaults; })(); var defaultsPrototype = Defaults.prototype; defaultsPrototype.actions = {}; defaultsPrototype.afterCreate = lifecycleNoopCb; defaultsPrototype.afterCreateCollection = lifecycleNoop; 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.beforeCreateCollection = lifecycleNoop; 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 = !!_utils['default'].w; defaultsPrototype.clearEmptyQueries = true; defaultsPrototype.computed = {}; defaultsPrototype.defaultAdapter = 'http'; defaultsPrototype.debug = false; defaultsPrototype.defaultValues = {}; defaultsPrototype.eagerEject = false; // TODO: Implement eagerInject in DS#create defaultsPrototype.eagerInject = false; defaultsPrototype.endpoint = ''; defaultsPrototype.error = console ? function (a, b, c) { return console[typeof console.error === 'function' ? 'error' : 'log'](a, b, c); } : false; defaultsPrototype.instanceEvents = !!_utils['default'].w; defaultsPrototype.fallbackAdapters = ['http']; defaultsPrototype.findStrictCache = false; defaultsPrototype.idAttribute = 'id'; defaultsPrototype.ignoredChanges = [/\$/]; defaultsPrototype.ignoreMissing = false; defaultsPrototype.keepChangeHistory = false; defaultsPrototype.linkRelations = true; defaultsPrototype.log = console ? function (a, b, c, d, e) { return console[typeof console.info === 'function' ? 'info' : 'log'](a, b, c, d, e); } : false; defaultsPrototype.logFn = function (a, b, c, d) { var _this = this; 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.methods = {}; defaultsPrototype.notify = !!_utils['default'].w; defaultsPrototype.omit = []; defaultsPrototype.onConflict = 'merge'; defaultsPrototype.reapAction = !!_utils['default'].w ? 'inject' : 'none'; defaultsPrototype.reapInterval = !!_utils['default'].w ? 30000 : false; defaultsPrototype.relationsEnumerable = false; defaultsPrototype.returnMeta = false; defaultsPrototype.resetHistoryOnInject = true; defaultsPrototype.strategy = 'single'; defaultsPrototype.upsert = !!_utils['default'].w; defaultsPrototype.useClass = true; defaultsPrototype.useFilter = false; defaultsPrototype.validate = lifecycleNoopCb; defaultsPrototype.defaultFilter = function (collection, resourceName, params, options) { var filtered = collection; var where = null; var reserved = { skip: '', offset: '', where: '', limit: '', orderBy: '', sort: '' }; params = params || {}; options = options || {}; if (_utils['default']._o(params.where)) { where = params.where; } else { where = {}; } if (options.allowSimpleWhere) { _utils['default'].forOwn(params, function (value, key) { if (!(key in reserved) && !(key in where)) { where[key] = { '==': value }; } }); } if (_utils['default'].isEmpty(where)) { where = null; } if (where) { filtered = _utils['default'].filter(filtered, function (attrs) { var first = true; var keep = true; _utils['default'].forOwn(where, function (clause, field) { if (!_utils['default']._o(clause)) { clause = { '==': clause }; } _utils['default'].forOwn(clause, function (term, op) { var expr = undefined; var isOr = op[0] === '|'; var val = _utils['default'].get(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 = !_utils['default'].intersection(val || [], term || []).length; } else if (op === 'isectNotEmpty') { expr = _utils['default'].intersection(val || [], term || []).length; } else if (op === 'in') { if (_utils['default']._s(term)) { expr = term.indexOf(val) !== -1; } else { expr = _utils['default'].contains(term, val); } } else if (op === 'notIn') { if (_utils['default']._s(term)) { expr = term.indexOf(val) === -1; } else { expr = !_utils['default'].contains(term, val); } } else if (op === 'contains') { if (_utils['default']._s(val)) { expr = val.indexOf(term) !== -1; } else { expr = _utils['default'].contains(val, term); } } else if (op === 'notContains') { if (_utils['default']._s(val)) { expr = val.indexOf(term) === -1; } else { expr = !_utils['default'].contains(val, term); } } if (expr !== undefined) { keep = first ? expr : isOr ? keep || expr : keep && expr; } first = false; }); }); return keep; }); } var orderBy = null; if (_utils['default']._s(params.orderBy)) { orderBy = [[params.orderBy, 'ASC']]; } else if (_utils['default']._a(params.orderBy)) { orderBy = params.orderBy; } if (!orderBy && _utils['default']._s(params.sort)) { orderBy = [[params.sort, 'ASC']]; } else if (!orderBy && _utils['default']._a(params.sort)) { orderBy = params.sort; } // Apply 'orderBy' if (orderBy) { (function () { var index = 0; _utils['default'].forEach(orderBy, function (def, i) { if (_utils['default']._s(def)) { orderBy[i] = [def, 'ASC']; } else if (!_utils['default']._a(def)) { throw new _errors['default'].IA('DS.filter("' + resourceName + '"[, params][, options]): ' + _utils['default'].toJson(def) + ': Must be a string or an array!', { params: { 'orderBy[i]': { actual: typeof def, expected: 'string|array' } } }); } }); filtered = _utils['default'].sort(filtered, function (a, b) { return compare(orderBy, index, a, b); }); })(); } var limit = _utils['default']._n(params.limit) ? params.limit : null; var skip = null; if (_utils['default']._n(params.skip)) { skip = params.skip; } else if (_utils['default']._n(params.offset)) { skip = params.offset; } // Apply 'limit' and 'skip' if (limit && skip) { filtered = _utils['default'].slice(filtered, skip, Math.min(filtered.length, skip + limit)); } else if (_utils['default']._n(limit)) { filtered = _utils['default'].slice(filtered, 0, Math.min(filtered.length, limit)); } else if (_utils['default']._n(skip)) { if (skip < filtered.length) { filtered = _utils['default'].slice(filtered, skip); } else { filtered = []; } } return filtered; }; var DS = (function () { function DS(options) { _classCallCheck(this, DS); var _this = this; options = options || {}; _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 = _utils['default'].observe; _utils['default'].forOwn(options, function (v, k) { if (k === 'omit') { _this.defaults.omit = v.concat(Defaults.prototype.omit); } else { _this.defaults[k] = v; } }); var P = _utils['default'].Promise; if (P && !P.prototype.spread) { P.prototype.spread = function (cb) { return this.then(function (arr) { return cb.apply(this, arr); }); }; } } _createClass(DS, [{ key: 'getAdapterName', value: function getAdapterName(options) { var errorIfNotExist = false; options = options || {}; if (_utils['default']._s(options)) { errorIfNotExist = true; options = { adapter: options }; } if (this.adapters[options.adapter]) { return options.adapter; } else if (errorIfNotExist) { throw new Error(options.adapter + ' is not a registered adapter!'); } else { return options.defaultAdapter; } } }, { key: 'getAdapter', value: function getAdapter(options) { options = options || {}; return this.adapters[this.getAdapterName(options)]; } }, { key: 'registerAdapter', value: function registerAdapter(name, Adapter, options) { var _this = this; options = options || {}; if (_utils['default'].isFunction(Adapter)) { _this.adapters[name] = new Adapter(options); } else { _this.adapters[name] = Adapter; } if (options['default']) { _this.defaults.defaultAdapter = name; } } }, { key: 'is', value: function is(resourceName, instance) { var definition = this.defs[resourceName]; if (!definition) { throw new _errors['default'].NER(resourceName); } return instance instanceof definition[definition['class']]; } }]); return DS; })(); var dsPrototype = DS.prototype; dsPrototype.getAdapterName.shorthand = false; dsPrototype.getAdapter.shorthand = false; dsPrototype.registerAdapter.shorthand = false; dsPrototype.errors = _errors['default']; dsPrototype.utils = _utils['default']; function addMethods(target, obj) { _utils['default'].forOwn(obj, function (v, k) { target[k] = v; target[k].before = function (fn) { var orig = target[k]; target[k] = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return orig.apply(this, fn.apply(this, args) || args); }; }; }); } addMethods(dsPrototype, _sync_methodsIndex['default']); addMethods(dsPrototype, _async_methodsIndex['default']); exports['default'] = DS; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { 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; } /* jshint eqeqeq:false */ /** * Mix of ES6 and CommonJS module imports because the interop of Babel + Webpack + ES6 modules + CommonJS isn't very good. */ var _errors = __webpack_require__(3); var BinaryHeap = __webpack_require__(7); var forEach = __webpack_require__(8); var slice = __webpack_require__(9); var forOwn = __webpack_require__(13); var contains = __webpack_require__(10); var deepMixIn = __webpack_require__(14); var pascalCase = __webpack_require__(18); var remove = __webpack_require__(11); var pick = __webpack_require__(15); var sort = __webpack_require__(12); var upperCase = __webpack_require__(19); var get = __webpack_require__(16); var set = __webpack_require__(17); var observe = __webpack_require__(6); var w = undefined; var objectProto = Object.prototype; var toString = objectProto.toString; var P = undefined; /** * Attempt to detect the global Promise constructor. * JSData will still work without one, as long you do something like this: * * var JSData = require('js-data'); * JSData.DSUtils.Promise = MyPromiseLib; */ try { P = Promise; } catch (err) { console.error('js-data requires a global Promise constructor!'); } var isArray = Array.isArray || function isArray(value) { return toString.call(value) == '[object Array]' || false; }; var isRegExp = function isRegExp(value) { return toString.call(value) == '[object RegExp]' || false; }; // adapted from lodash.isString var isString = function isString(value) { return typeof value == 'string' || value && typeof value == 'object' && toString.call(value) == '[object String]' || false; }; var isObject = function isObject(value) { return toString.call(value) == '[object Object]' || false; }; // adapted from lodash.isDate var isDate = function isDate(value) { return value && typeof value == 'object' && toString.call(value) == '[object Date]' || false; }; // adapted from lodash.isNumber var isNumber = function isNumber(value) { var type = typeof value; return type == 'number' || value && type == 'object' && toString.call(value) == '[object Number]' || false; }; // adapted from lodash.isFunction var 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 var isStringOrNumber = function isStringOrNumber(value) { return isString(value) || isNumber(value); }; var isStringOrNumberErr = function isStringOrNumberErr(field) { return new _errors['default'].IA('"' + field + '" must be a string or a number!'); }; var isObjectErr = function isObjectErr(field) { return new _errors['default'].IA('"' + field + '" must be an object!'); }; var isArrayErr = function isArrayErr(field) { return new _errors['default'].IA('"' + field + '" must be an array!'); }; // adapted from mout.isEmpty var isEmpty = function isEmpty(val) { if (val == null) { // jshint ignore:line // 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; } }; // Find the intersection between two arrays var intersection = function intersection(array1, array2) { if (!array1 || !array2) { return []; } var result = []; var item = undefined; for (var i = 0, _length = array1.length; i < _length; i++) { item = array1[i]; if (contains(result, item)) { continue; } if (contains(array2, item)) { result.push(item); } } return result; }; var filter = function filter(array, cb, thisObj) { var results = []; forEach(array, function (value, key, arr) { if (cb(value, key, arr)) { results.push(value); } }, thisObj); return results; }; /** * Attempt to detect whether we are in the browser. */ try { w = window; w = {}; } catch (e) { w = null; } /** * Event mixin. Usage: * * function handler() { ... } * Events(myObject); * myObject.on('foo', handler); * myObject.emit('foo', 'some', 'data'); * myObject.off('foo', handler); */ 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 () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var listeners = events[args.shift()] || []; if (listeners) { for (var i = 0; i < listeners.length; i++) { listeners[i].f.apply(listeners[i].c, args); } } }; } /** * Lifecycle hooks that should support promises. */ var toPromisify = ['beforeValidate', 'validate', 'afterValidate', 'beforeCreate', 'afterCreate', 'beforeUpdate', 'afterUpdate', 'beforeDestroy', 'afterDestroy']; /** * Return whether "prop" is in the blacklist. */ var isBlacklisted = observe.isBlacklisted; // adapted from angular.copy var copy = function copy(source, destination, stackSource, stackDest, blacklist) { if (!destination) { destination = source; if (source) { if (isArray(source)) { destination = copy(source, [], stackSource, stackDest, blacklist); } 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)) { destination = copy(source, Object.create(Object.getPrototypeOf(source)), stackSource, stackDest, blacklist); } } } 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 = undefined; if (isArray(source)) { var i = undefined; destination.length = 0; for (i = 0; i < source.length; i++) { result = copy(source[i], null, stackSource, stackDest, blacklist); 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)) { if (isBlacklisted(key, blacklist)) { continue; } result = copy(source[key], null, stackSource, stackDest, blacklist); if (isObject(source[key])) { stackSource.push(source[key]); stackDest.push(result); } destination[key] = result; } } } } return destination; }; // adapted from angular.equals var equals = function equals(_x, _x2) { var _again = true; _function: while (_again) { var o1 = _x, o2 = _x2; t1 = t2 = length = key = keySet = undefined; _again = false; 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) { // jshint ignore:line 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; } _x = o1.getTime(); _x2 = o2.getTime(); _again = true; continue _function; } 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; } }; /** * Given either an instance or the primary key of an instance, return the primary key. */ var resolveId = function resolveId(definition, idOrInstance) { if (isString(idOrInstance) || isNumber(idOrInstance)) { return idOrInstance; } else if (idOrInstance && definition) { return idOrInstance[definition.idAttribute] || idOrInstance; } else { return idOrInstance; } }; /** * Given either an instance or the primary key of an instance, return the instance. */ var resolveItem = function resolveItem(resource, idOrInstance) { if (resource && (isString(idOrInstance) || isNumber(idOrInstance))) { return resource.index[idOrInstance] || idOrInstance; } else { return idOrInstance; } }; var isValidString = function isValidString(val) { return val != null && val !== ''; // jshint ignore:line }; var join = function join(items, separator) { separator = separator || ''; return filter(items, isValidString).join(separator); }; var makePath = function makePath() { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } var result = join(args, '/'); return result.replace(/([^:\/]|^)\/{2,}/g, '$1/'); }; exports['default'] = { Promise: P, /** * Method to wrap an "options" object so that it will inherit from * some parent object, such as a resource definition. */ _: function _(parent, options) { var _this = this; options = options || {}; if (options && options.constructor === parent.constructor) { return options; } else if (!isObject(options)) { throw new _errors['default'].IA('"options" must be an object!'); } forEach(toPromisify, function (name) { if (typeof options[name] === 'function' && options[name].toString().indexOf('for (var _len = arg') === -1) { options[name] = _this.promisify(options[name]); } }); // Dynamic constructor function var O = function Options(attrs) { var self = this; forOwn(attrs, function (value, key) { self[key] = value; }); }; // Inherit from some parent object O.prototype = parent; // Give us a way to get the original options back. O.prototype.orig = function () { var orig = {}; forOwn(this, function (value, key) { orig[key] = value; }); return orig; }; return new O(options); }, _n: isNumber, _s: isString, _sn: isStringOrNumber, _snErr: isStringOrNumberErr, _o: isObject, _oErr: isObjectErr, _a: isArray, _aErr: isArrayErr, compute: function compute(fn, field) { var _this = this; var args = []; forEach(fn.deps, function (dep) { args.push(get(_this, dep)); }); // compute property set(_this, field, fn[fn.length - 1].apply(_this, args)); }, contains: contains, copy: copy, deepMixIn: deepMixIn, diffObjectFromOldObject: observe.diffObjectFromOldObject, BinaryHeap: BinaryHeap, equals: equals, Events: Events, filter: filter, fillIn: function fillIn(target, obj) { forOwn(obj, function (v, k) { if (!(k in target)) { target[k] = v; } }); return target; }, forEach: forEach, forOwn: forOwn, fromJson: function fromJson(json) { return isString(json) ? JSON.parse(json) : json; }, get: get, intersection: intersection, isArray: isArray, isBlacklisted: isBlacklisted, isEmpty: isEmpty, isFunction: isFunction, isObject: isObject, isNumber: isNumber, isString: isString, makePath: makePath, observe: observe, omit: function omit(obj, bl) { var toRemove = []; forOwn(obj, function (v, k) { if (isBlacklisted(k, bl)) { toRemove.push(k); } }); forEach(toRemove, function (k) { delete obj[k]; }); return obj; }, pascalCase: pascalCase, pick: pick, // Turn the given node-style callback function into one that can return a promise. promisify: function promisify(fn, target) { var _this = this; if (!fn) { return; } else if (typeof fn !== 'function') { throw new Error('Can only promisify functions!'); } return function () { for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } return new _this.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: remove, set: set, slice: slice, sort: sort, toJson: JSON.stringify, updateTimestamp: function updateTimestamp(timestamp) { var newTimestamp = typeof Date.now === 'function' ? Date.now() : new Date().getTime(); if (timestamp && newTimestamp <= timestamp) { return timestamp + 1; } else { return newTimestamp; } }, upperCase: upperCase, // Return a copy of "object" with cycles removed. removeCircular: function removeCircular(object) { return (function rmCirc(value, ctx) { var i = undefined; var nu = undefined; if (typeof value === 'object' && value !== null && !(value instanceof Boolean) && !(value instanceof Date) && !(value instanceof Number) && !(value instanceof RegExp) && !(value instanceof String)) { // check if current object points back to itself var cur = ctx.cur; var parent = ctx.ctx; while (parent) { if (parent.cur === cur) { return undefined; } parent = parent.ctx; } if (isArray(value)) { nu = []; for (i = 0; i < value.length; i += 1) { nu[i] = rmCirc(value[i], { ctx: ctx, cur: value[i] }); } } else { nu = {}; forOwn(value, function (v, k) { nu[k] = rmCirc(value[k], { ctx: ctx, cur: value[k] }); }); } return nu; } return value; })(object, { ctx: null, cur: object }); }, resolveItem: resolveItem, resolveId: resolveId, respond: function respond(response, meta, options) { if (options.returnMeta === 'array') { return [response, meta]; } else if (options.returnMeta === 'object') { return { response: response, meta: meta }; } else { return response; } }, w: w, // This is where the magic of relations happens. applyRelationGettersToTarget: function applyRelationGettersToTarget(store, definition, target) { this.forEach(definition.relationList, function (def) { var relationName = def.relation; var enumerable = typeof def.enumerable === 'boolean' ? def.enumerable : !!definition.relationsEnumerable; if (typeof def.link === 'boolean' ? def.link : !!definition.linkRelations) { delete target[def.localField]; if (def.type === 'belongsTo') { Object.defineProperty(target, def.localField, { enumerable: enumerable, get: function get() { return this[def.localKey] ? definition.getResource(relationName).get(this[def.localKey]) : undefined; }, set: function set() {} }); } else if (def.type === 'hasMany') { Object.defineProperty(target, def.localField, { enumerable: enumerable, get: function get() { var params = {}; if (def.foreignKey) { params[def.foreignKey] = this[definition.idAttribute]; return definition.getResource(relationName).defaultFilter.call(store, store.s[relationName].collection, relationName, params, { allowSimpleWhere: true }); } else if (def.localKeys) { params.where = _defineProperty({}, definition.getResource(relationName).idAttribute, { 'in': this[def.localKeys] }); return definition.getResource(relationName).defaultFilter.call(store, store.s[relationName].collection, relationName, params); } return undefined; }, set: function set() {} }); } else if (def.type === 'hasOne') { if (def.localKey) { Object.defineProperty(target, def.localField, { enumerable: enumerable, get: function get() { return this[def.localKey] ? definition.getResource(relationName).get(this[def.localKey]) : undefined; }, set: function set() {} }); } else { Object.defineProperty(target, def.localField, { enumerable: enumerable, get: function get() { var params = {}; params[def.foreignKey] = this[definition.idAttribute]; var items = params[def.foreignKey] ? definition.getResource(relationName).defaultFilter.call(store, store.s[relationName].collection, relationName, params, { allowSimpleWhere: true }) : []; if (items.length) { return items[0]; } return undefined; }, set: function set() {} }); } } } }); } }; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } /** * Thrown during a method call when an argument passed into the method is invalid. */ var IllegalArgumentError = (function (_Error) { function IllegalArgumentError(message) { _classCallCheck(this, IllegalArgumentError); _get(Object.getPrototypeOf(IllegalArgumentError.prototype), 'constructor', this).call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } this.type = this.constructor.name; this.message = message; } _inherits(IllegalArgumentError, _Error); return IllegalArgumentError; })(Error); /** * Thrown when an invariant is violated or unrecoverable error is encountered during execution. */ var RuntimeError = (function (_Error2) { function RuntimeError(message) { _classCallCheck(this, RuntimeError); _get(Object.getPrototypeOf(RuntimeError.prototype), 'constructor', this).call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } this.type = this.constructor.name; this.message = message; } _inherits(RuntimeError, _Error2); return RuntimeError; })(Error); /** * Thrown when attempting to access or work with a non-existent resource. */ var NonexistentResourceError = (function (_Error3) { function NonexistentResourceError(resourceName) { _classCallCheck(this, NonexistentResourceError); _get(Object.getPrototypeOf(NonexistentResourceError.prototype), 'constructor', this).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!'; } _inherits(NonexistentResourceError, _Error3); return NonexistentResourceError; })(Error); exports['default'] = { IllegalArgumentError: IllegalArgumentError, IA: IllegalArgumentError, RuntimeError: RuntimeError, R: RuntimeError, NonexistentResourceError: NonexistentResourceError, NER: NonexistentResourceError }; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { var _utils = __webpack_require__(2); var _errors = __webpack_require__(3); var _defineResource = __webpack_require__(28); var _eject = __webpack_require__(29); var _ejectAll = __webpack_require__(30); var _filter = __webpack_require__(31); var _inject = __webpack_require__(32); var NER = _errors['default'].NER; var IA = _errors['default'].IA; var R = _errors['default'].R; function diffIsEmpty(diff) { return !(_utils['default'].isEmpty(diff.added) && _utils['default'].isEmpty(diff.removed) && _utils['default'].isEmpty(diff.changed)); } exports['default'] = { /** * Return the changes for the given item, if any. * * @param resourceName The name of the type of resource of the item whose changes are to be returned. * @param id The primary key of the item whose changes are to be returned. * @param options Optional configuration. * @param options.ignoredChanges Array of strings or regular expressions of fields, the changes of which are to be ignored. * @returns The changes of the given item, if any. */ changes: function changes(resourceName, id, options) { var _this = this; var definition = _this.defs[resourceName]; options = options || {}; id = _utils['default'].resolveId(definition, id); if (!definition) { throw new NER(resourceName); } else if (!_utils['default']._sn(id)) { throw _utils['default']._snErr('id'); } options = _utils['default']._(definition, options); var item = definition.get(id); if (item) { var _ret = (function () { if (_utils['default'].w) { // force observation handler to be fired for item if there are changes and `Object.observe` is not available _this.s[resourceName].observers[id].deliver(); } var ignoredChanges = options.ignoredChanges || []; // add linked relations to list of ignored changes _utils['default'].forEach(definition.relationFields, function (field) { if (!_utils['default'].contains(ignoredChanges, field)) { ignoredChanges.push(field); } }); // calculate changes var diff = _utils['default'].diffObjectFromOldObject(item, _this.s[resourceName].previousAttributes[id], _utils['default'].equals, ignoredChanges); // remove functions from diff _utils['default'].forOwn(diff, function (changeset, name) { var toKeep = []; _utils['default'].forOwn(changeset, function (value, field) { if (!_utils['default'].isFunction(value)) { toKeep.push(field); } }); diff[name] = _utils['default'].pick(diff[name], toKeep); }); // definitely ignore changes to linked relations _utils['default'].forEach(definition.relationFields, function (field) { delete diff.added[field]; delete diff.removed[field]; delete diff.changed[field]; }); return { v: diff }; })(); if (typeof _ret === 'object') return _ret.v; } }, /** * Return the change history of the given item, if any. * * @param resourceName The name of the type of resource of the item whose change history is to be returned. * @param id The primary key of the item whose change history is to be returned. * @returns The change history of the given item, if any. */ changeHistory: function changeHistory(resourceName, id) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; id = _utils['default'].resolveId(definition, id); if (resourceName && !_this.defs[resourceName]) { throw new NER(resourceName); } else if (id && !_utils['default']._sn(id)) { throw _utils['default']._snErr('id'); } if (!definition.keepChangeHistory) { definition.errorFn('changeHistory is disabled for this resource!'); } else { if (resourceName) { var item = definition.get(id); if (item) { return resource.changeHistories[id]; } } else { return resource.changeHistory; } } }, /** * Re-compute the computed properties of the given item. * * @param resourceName The name of the type of resource of the item whose computed properties are to be re-computed. * @param instance The instance whose computed properties are to be re-computed. * @returns The item whose computed properties were re-computed. */ compute: function compute(resourceName, instance) { var _this = this; var definition = _this.defs[resourceName]; instance = _utils['default'].resolveItem(_this.s[resourceName], instance); if (!definition) { throw new NER(resourceName); } else if (!instance) { throw new R('Item not in the store!'); } else if (!_utils['default']._o(instance) && !_utils['default']._sn(instance)) { throw new IA('"instance" must be an object, string or number!'); } // re-compute all computed properties _utils['default'].forOwn(definition.computed, function (fn, field) { _utils['default'].compute.call(instance, fn, field); }); return instance; }, /** * Factory function to create an instance of the specified Resource. * * @param resourceName The name of the type of resource of which to create an instance. * @param attrs Hash of properties with which to initialize the instance. * @param options Optional configuration. * @param options.defaults Default values with which to initialize the instance. * @returns The new instance. */ createInstance: function createInstance(resourceName, attrs, options) { var definition = this.defs[resourceName]; var item = undefined; attrs = attrs || {}; if (!definition) { throw new NER(resourceName); } else if (attrs && !_utils['default'].isObject(attrs)) { throw new IA('"attrs" must be an object!'); } options = _utils['default']._(definition, options); // lifecycle options.beforeCreateInstance(options, attrs); // grab instance constructor function from Resource definition var Constructor = definition[definition['class']]; // create instance item = new Constructor(); // add default values if (options.defaultValues) { _utils['default'].deepMixIn(item, options.defaultValues); } _utils['default'].deepMixIn(item, attrs); // compute computed properties if (definition.computed) { definition.compute(item); } // lifecycle options.afterCreateInstance(options, item); return item; }, /** * Create a new collection of the specified Resource. * * @param resourceName The name of the type of resource of which to create a collection * @param arr Possibly empty array of data from which to create the collection. * @param params The criteria by which to filter items. Will be passed to `DS#findAll` if `fetch` is called. See http://www.js-data.io/docs/query-syntax * @param options Optional configuration. * @param options.notify Whether to call the beforeCreateCollection and afterCreateCollection lifecycle hooks.. * @returns The new collection. */ createCollection: function createCollection(resourceName, arr, params, options) { var _this = this; var definition = _this.defs[resourceName]; arr = arr || []; params = params || {}; if (!definition) { throw new NER(resourceName); } else if (arr && !_utils['default'].isArray(arr)) { throw new IA('"arr" must be an array!'); } options = _utils['default']._(definition, options); // lifecycle options.beforeCreateCollection(options, arr); // define the API for this collection Object.defineProperties(arr, { /** * Call DS#findAll with the params of this collection, filling the collection with the results. */ fetch: { value: function value(params, options) { var __this = this; __this.params = params || __this.params; return definition.findAll(__this.params, options).then(function (data) { if (data === __this) { return __this; } data.unshift(__this.length); data.unshift(0); __this.splice.apply(__this, data); data.shift(); data.shift(); if (data.$$injected) { _this.s[resourceName].queryData[_utils['default'].toJson(__this.params)] = __this; __this.$$injected = true; } return __this; }); } }, // params for this collection. See http://www.js-data.io/docs/query-syntax params: { value: params, writable: true }, // name of the resource type of this collection resourceName: { value: resourceName } }); // lifecycle options.afterCreateCollection(options, arr); return arr; }, defineResource: _defineResource['default'], digest: function digest() { this.observe.Platform.performMicrotaskCheckpoint(); }, eject: _eject['default'], ejectAll: _ejectAll['default'], filter: _filter['default'], /** * Return the item with the given primary key if its in the store. * * @param resourceName The name of the type of resource of the item to retrieve. * @param id The primary key of the item to retrieve. * @param options Optional configuration. * @returns The item with the given primary key if it's in the store. */ get: function get(resourceName, id, options) { var _this = this; var definition = _this.defs[resourceName]; if (!definition) { throw new NER(resourceName); } else if (!_utils['default']._sn(id)) { throw _utils['default']._snErr('id'); } options = _utils['default']._(definition, options); // return the item if it exists return _this.s[resourceName].index[id]; }, /** * Return the items in the store that have the given primary keys. * * @param resourceName The name of the type of resource of the items to retrieve. * @param ids The primary keys of the items to retrieve. * @returns The items with the given primary keys if they're in the store. */ getAll: 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 && !_utils['default']._a(ids)) { throw _utils['default']._aErr('ids'); } if (_utils['default']._a(ids)) { // return just the items with the given primary keys var _length = ids.length; for (var i = 0; i < _length; i++) { if (resource.index[ids[i]]) { collection.push(resource.index[ids[i]]); } } } else { // most efficient of retrieving ALL items from the store collection = resource.collection.slice(); } return collection; }, /** * Return the whether the item with the given primary key has any changes. * * @param resourceName The name of the type of resource of the item. * @param id The primary key of the item. * @returns Whether the item with the given primary key has any changes. */ hasChanges: function hasChanges(resourceName, id) { var _this = this; var definition = _this.defs[resourceName]; id = _utils['default'].resolveId(definition, id); if (!definition) { throw new NER(resourceName); } else if (!_utils['default']._sn(id)) { throw _utils['default']._snErr('id'); } return definition.get(id) ? diffIsEmpty(definition.changes(id)) : false; }, inject: _inject['default'], /** * Return the timestamp from the last time the item with the given primary key was changed. * * @param resourceName The name of the type of resource of the item. * @param id The primary key of the item. * @returns Timestamp from the last time the item was changed. */ lastModified: function lastModified(resourceName, id) { var definition = this.defs[resourceName]; var resource = this.s[resourceName]; id = _utils['default'].resolveId(definition, id); if (!definition) { throw new NER(resourceName); } if (id) { if (!(id in resource.modified)) { resource.modified[id] = 0; } return resource.modified[id]; } return resource.collectionModified; }, /** * Return the timestamp from the last time the item with the given primary key was saved via an adapter. * * @param resourceName The name of the type of resource of the item. * @param id The primary key of the item. * @returns Timestamp from the last time the item was saved. */ lastSaved: function lastSaved(resourceName, id) { var definition = this.defs[resourceName]; var resource = this.s[resourceName]; id = _utils['default'].resolveId(definition, id); if (!definition) { throw new NER(resourceName); } if (!(id in resource.saved)) { resource.saved[id] = 0; } return resource.saved[id]; }, /** * Return the previous attributes of the item with the given primary key before it was changed. * * @param resourceName The name of the type of resource of the item. * @param id The primary key of the item. * @returns The previous attributes of the item */ previous: function previous(resourceName, id) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; id = _utils['default'].resolveId(definition, id); if (!definition) { throw new NER(resourceName); } else if (!_utils['default']._sn(id)) { throw _utils['default']._snErr('id'); } // return resource from cache return resource.previousAttributes[id] ? _utils['default'].copy(resource.previousAttributes[id]) : undefined; } }; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { var _create = __webpack_require__(33); var _destroy = __webpack_require__(34); var _destroyAll = __webpack_require__(35); var _find = __webpack_require__(36); var _findAll = __webpack_require__(37); var _loadRelations = __webpack_require__(38); var _reap = __webpack_require__(39); var _save = __webpack_require__(40); var _update = __webpack_require__(41); var _updateAll = __webpack_require__(42); exports['default'] = { create: _create['default'], destroy: _destroy['default'], destroyAll: _destroyAll['default'], find: _find['default'], findAll: _findAll['default'], loadRelations: _loadRelations['default'], reap: _reap['default'], refresh: function refresh(resourceName, id, options) { var _this = this; var DSUtils = _this.utils; 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; resolve(_this.get(resourceName, id)); } }).then(function (item) { return item ? _this.find(resourceName, id, options) : item; }); }, refreshAll: function refreshAll(resourceName, params, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; params = params || {}; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._o(params)) { reject(DSUtils._oErr('params')); } else { options = DSUtils._(definition, options); options.bypassCache = true; resolve(_this.filter(resourceName, params, options)); } }).then(function (existing) { options.bypassCache = true; return _this.findAll(resourceName, params, options).then(function (found) { DSUtils.forEach(existing, function (item) { if (found.indexOf(item) === -1) { definition.eject(item); } }); return found; }); }); }, save: _save['default'], update: _update['default'], updateAll: _updateAll['default'] }; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { /* * 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 */ // 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 in diffObjectFromOldObject to ignore changes to certain properties // Removed all code related to: // - ArrayObserver // - ArraySplice // - PathObserver // - CompoundObserver // - Path // - ObserverTransform (function(global) { 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(); 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 (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(){ 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); } }; } 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; 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_; } }); 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 }; } // Export the observe-js object for **Node.js**, with backwards-compatibility // for the old `require()` API. Also ensure `exports` is not a DOM Element. // If we're in the browser, export as a global object. global.Observer = Observer; global.isBlacklisted = isBlacklisted; global.Observer.runEOM_ = runEOM; global.Observer.observerSentinel_ = observerSentinel; // for testing. global.Observer.hasObjectObserve = hasObserve; global.diffObjectFromOldObject = diffObjectFromOldObject; global.ObjectObserver = ObjectObserver; })(exports); /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { /*! * yabh * @version 1.0.1 - Homepage <http://jmdobry.github.io/yabh/> * @author Jason Dobry <[email protected]> * @copyright (c) 2015 Jason Dobry * @license MIT <https://github.com/jmdobry/yabh/blob/master/LICENSE> * * @overview Yet another Binary Heap. */ (function webpackUniversalModuleDefinition(root, factory) { if(true) module.exports = factory(); else if(typeof define === 'function' && define.amd) define("yabh", factory); else if(typeof exports === 'object') exports["BinaryHeap"] = factory(); else root["BinaryHeap"] = factory(); })(this, function() { 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__) { var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); Object.defineProperty(exports, '__esModule', { value: true }); /** * @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. */ var bubbleDown = 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; } } }; var BinaryHeap = (function () { function BinaryHeap(weightFunc, compareFunc) { _classCallCheck(this, BinaryHeap); if (!weightFunc) { weightFunc = function (x) { return x; }; } if (!compareFunc) { compareFunc = function (x, y) { return x === y; }; } if (typeof weightFunc !== 'function') { throw new Error('BinaryHeap([weightFunc][, compareFunc]): "weightFunc" must be a function!'); } if (typeof compareFunc !== 'function') { throw new Error('BinaryHeap([weightFunc][, compareFunc]): "compareFunc" must be a function!'); } this.weightFunc = weightFunc; this.compareFunc = compareFunc; this.heap = []; } _createClass(BinaryHeap, [{ key: 'push', value: function push(node) { this.heap.push(node); bubbleUp(this.heap, this.weightFunc, this.heap.length - 1); } }, { key: 'peek', value: function peek() { return this.heap[0]; } }, { key: 'pop', value: function pop() { var front = this.heap[0]; var end = this.heap.pop(); if (this.heap.length > 0) { this.heap[0] = end; bubbleDown(this.heap, this.weightFunc, 0); } return front; } }, { key: 'remove', value: function remove(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; } }, { key: 'removeAll', value: function removeAll() { this.heap = []; } }, { key: 'size', value: function size() { return this.heap.length; } }]); return BinaryHeap; })(); exports['default'] = BinaryHeap; module.exports = exports['default']; /***/ } /******/ ]) }); ; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { /** * 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; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { /** * 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; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { var indexOf = __webpack_require__(20); /** * If array contains values. */ function contains(arr, val) { return indexOf(arr, val) !== -1; } module.exports = contains; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { var indexOf = __webpack_require__(20); /** * 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; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { /** * 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; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { var hasOwn = __webpack_require__(21); var forIn = __webpack_require__(22); /** * 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; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { var forOwn = __webpack_require__(13); var isPlainObject = __webpack_require__(23); /** * 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; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { var slice = __webpack_require__(9); /** * 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; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { var isPrimitive = __webpack_require__(24); /** * 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; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { var namespace = __webpack_require__(25); /** * 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; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(26); var camelCase = __webpack_require__(27); var upperCase = __webpack_require__(19); /** * camelCase + UPPERCASE first char */ function pascalCase(str){ str = toString(str); return camelCase(str).replace(/^[a-z]/, upperCase); } module.exports = pascalCase; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(26); /** * "Safer" String.toUpperCase() */ function upperCase(str){ str = toString(str); return str.toUpperCase(); } module.exports = upperCase; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { /** * 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; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { /** * Safer Object.hasOwnProperty */ function hasOwn(obj, prop){ return Object.prototype.hasOwnProperty.call(obj, prop); } module.exports = hasOwn; /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { var hasOwn = __webpack_require__(21); 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; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { /** * Checks if the value is created by the `Object` constructor. */ function isPlainObject(value) { return (!!value && typeof value === 'object' && value.constructor === Object); } module.exports = isPlainObject; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { /** * 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; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { var forEach = __webpack_require__(8); /** * 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; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { /** * 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; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(26); var replaceAccents = __webpack_require__(43); var removeNonWord = __webpack_require__(44); var upperCase = __webpack_require__(19); var lowerCase = __webpack_require__(45); /** * 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; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { exports['default'] = defineResource; /*jshint evil:true, loopfunc:true*/ var _utils = __webpack_require__(2); var _errors = __webpack_require__(3); /** * These are DS methods that will be proxied by instances. e.g. * * var store = new JSData.DS(); * var User = store.defineResource('user'); * var user = User.createInstance({ id: 1 }); * * store.update(resourceName, id, attrs[, options]) // DS method * User.update(id, attrs[, options]) // DS method proxied on a Resource * user.DSUpdate(attrs[, options]) // DS method proxied on an Instance */ var instanceMethods = ['compute', 'eject', 'refresh', 'save', 'update', 'destroy', 'loadRelations', 'changeHistory', 'changes', 'hasChanges', 'lastModified', 'lastSaved', 'previous']; function defineResource(definition) { var _this = this; var definitions = _this.defs; /** * This allows the name-only definition shorthand. * store.defineResource('user') is the same as store.defineResource({ name: 'user'}) */ if (_utils['default']._s(definition)) { definition = { name: definition.replace(/\s/gi, '') }; } if (!_utils['default']._o(definition)) { throw _utils['default']._oErr('definition'); } else if (!_utils['default']._s(definition.name)) { throw new _errors['default'].IA('"name" must be a string!'); } else if (definitions[definition.name]) { throw new _errors['default'].R(definition.name + ' is already registered!'); } /** * Dynamic Resource constructor function. * * A Resource inherits from the defaults of the data store that created it. */ function Resource(options) { this.defaultValues = {}; this.methods = {}; this.computed = {}; _utils['default'].deepMixIn(this, options); var parent = _this.defaults; if (definition['extends'] && definitions[definition['extends']]) { parent = definitions[definition['extends']]; } _utils['default'].fillIn(this.defaultValues, parent.defaultValues); _utils['default'].fillIn(this.methods, parent.methods); _utils['default'].fillIn(this.computed, parent.computed); this.endpoint = 'endpoint' in options ? options.endpoint : this.name; } try { var def; var _class; var _ret = (function () { // Resources can inherit from another resource instead of inheriting directly from the data store defaults. if (definition['extends'] && definitions[definition['extends']]) { // Inherit from another resource Resource.prototype = definitions[definition['extends']]; } else { // Inherit from global defaults Resource.prototype = _this.defaults; } definitions[definition.name] = new Resource(definition); def = definitions[definition.name]; def.getResource = function (resourceName) { return _this.defs[resourceName]; }; if (!_utils['default']._s(def.idAttribute)) { throw new _errors['default'].IA('"idAttribute" must be a string!'); } // Setup nested parent configuration if (def.relations) { def.relationList = []; def.relationFields = []; _utils['default'].forOwn(def.relations, function (relatedModels, type) { _utils['default'].forOwn(relatedModels, function (defs, relationName) { if (!_utils['default']._a(defs)) { relatedModels[relationName] = [defs]; } _utils['default'].forEach(relatedModels[relationName], function (d) { d.type = type; d.relation = relationName; d.name = def.name; def.relationList.push(d); if (d.localField) { def.relationFields.push(d.localField); } }); }); }); if (def.relations.belongsTo) { _utils['default'].forOwn(def.relations.belongsTo, function (relatedModel, modelName) { _utils['default'].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); } } // Create the wrapper class for the new resource _class = def['class'] = _utils['default'].pascalCase(def.name); try { if (typeof def.useClass === 'function') { eval('function ' + _class + '() { def.useClass.call(this); }'); def[_class] = eval(_class); def[_class].prototype = (function (proto) { function Ctor() {} Ctor.prototype = proto; return new Ctor(); })(def.useClass.prototype); } else { eval('function ' + _class + '() {}'); def[_class] = eval(_class); } } catch (e) { def[_class] = function () {}; } // Apply developer-defined instance methods _utils['default'].forOwn(def.methods, function (fn, m) { def[_class].prototype[m] = fn; }); /** * var user = User.createInstance({ id: 1 }); * user.set('foo', 'bar'); */ def[_class].prototype.set = function (key, value) { var _this2 = this; _utils['default'].set(this, key, value); def.compute(this); if (def.instanceEvents) { setTimeout(function () { _this2.emit('DS.change', def, _this2); }, 0); } def.handleChange(this); return this; }; /** * var user = User.createInstance({ id: 1 }); * user.get('id'); // 1 */ def[_class].prototype.get = function (key) { return _utils['default'].get(this, key); }; if (def.instanceEvents) { _utils['default'].Events(def[_class].prototype); } // Setup the relation links _utils['default'].applyRelationGettersToTarget(_this, def, def[_class].prototype); var parentOmit = null; if (!def.hasOwnProperty('omit')) { parentOmit = def.omit; def.omit = []; } else { parentOmit = _this.defaults.omit; } def.omit = def.omit.concat(parentOmit || []); // Prepare for computed properties _utils['default'].forOwn(def.computed, function (fn, field) { if (_utils['default'].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!'); } def.omit.push(field); 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); _utils['default'].forEach(deps, function (val, index) { deps[index] = val.trim(); }); fn.deps = _utils['default'].filter(deps, function (dep) { return !!dep; }); }); // add instance proxies of DS methods _utils['default'].forEach(instanceMethods, function (name) { def[_class].prototype['DS' + _utils['default'].pascalCase(name)] = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } args.unshift(this[def.idAttribute] || this); args.unshift(def.name); return _this[name].apply(_this, args); }; }); // manually add instance proxy for DS#create def[_class].prototype.DSCreate = function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } args.unshift(this); args.unshift(def.name); return _this.create.apply(_this, args); }; // Initialize store data for the new resource _this.s[def.name] = { collection: [], expiresHeap: new _utils['default'].BinaryHeap(function (x) { return x.expires; }, function (x, y) { return x.item === y; }), completedQueries: {}, queryData: {}, pendingQueries: {}, index: {}, modified: {}, saved: {}, previousAttributes: {}, observers: {}, changeHistories: {}, changeHistory: [], collectionModified: 0 }; var resource = _this.s[def.name]; // start the reaping if (def.reapInterval) { setInterval(function () { return def.reap(); }, def.reapInterval); } // proxy DS methods with shorthand ones var fns = ['registerAdapter', 'getAdapterName', 'getAdapter', 'is']; for (var key in _this) { if (typeof _this[key] === 'function') { fns.push(key); } } /** * Create the Resource shorthands that proxy DS methods. e.g. * * var store = new JSData.DS(); * var User = store.defineResource('user'); * * store.update(resourceName, id, attrs[, options]) // DS method * User.update(id, attrs[, options]) // DS method proxied on a Resource */ _utils['default'].forEach(fns, function (key) { var k = key; if (_this[k].shorthand !== false) { def[k] = function () { for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } args.unshift(def.name); return _this[k].apply(_this, args); }; def[k].before = function (fn) { var orig = def[k]; def[k] = function () { for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } return orig.apply(def, fn.apply(def, args) || args); }; }; } else { def[k] = function () { for (var _len5 = arguments.length, args = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { args[_key5] = arguments[_key5]; } return _this[k].apply(_this, args); }; } }); def.beforeValidate = _utils['default'].promisify(def.beforeValidate); def.validate = _utils['default'].promisify(def.validate); def.afterValidate = _utils['default'].promisify(def.afterValidate); def.beforeCreate = _utils['default'].promisify(def.beforeCreate); def.afterCreate = _utils['default'].promisify(def.afterCreate); def.beforeUpdate = _utils['default'].promisify(def.beforeUpdate); def.afterUpdate = _utils['default'].promisify(def.afterUpdate); def.beforeDestroy = _utils['default'].promisify(def.beforeDestroy); def.afterDestroy = _utils['default'].promisify(def.afterDestroy); var defaultAdapter = undefined; if (def.hasOwnProperty('defaultAdapter')) { defaultAdapter = def.defaultAdapter; } // setup "actions" _utils['default'].forOwn(def.actions, function (action, name) { if (def[name] && !def.actions[name]) { throw new Error('Cannot override existing method "' + name + '"!'); } action.request = action.request || function (config) { return config; }; action.response = action.response || function (response) { return response; }; action.responseError = action.responseError || function (err) { return _utils['default'].Promise.reject(err); }; def[name] = function (id, options) { if (_utils['default']._o(id)) { options = id; } options = options || {}; var adapter = def.getAdapter(action.adapter || defaultAdapter || 'http'); var config = _utils['default'].deepMixIn({}, action); if (!options.hasOwnProperty('endpoint') && config.endpoint) { options.endpoint = config.endpoint; } if (typeof options.getEndpoint === 'function') { config.url = options.getEndpoint(def, options); } else { var args = [options.basePath || adapter.defaults.basePath || def.basePath, adapter.getEndpoint(def, _utils['default']._sn(id) ? id : null, options)]; if (_utils['default']._sn(id)) { args.push(id); } args.push(action.pathname || name); config.url = _utils['default'].makePath.apply(null, args); } config.method = config.method || 'GET'; _utils['default'].deepMixIn(config, options); return new _utils['default'].Promise(function (r) { return r(config); }).then(options.request || action.request).then(function (config) { return adapter.HTTP(config); }).then(options.response || action.response, options.responseError || action.responseError); }; }); // mix in events _utils['default'].Events(def); def.handleChange = function (data) { resource.collectionModified = _utils['default'].updateTimestamp(resource.collectionModified); if (def.notify) { setTimeout(function () { def.emit('DS.change', def, data); }, 0); } }; return { v: def }; })(); if (typeof _ret === 'object') return _ret.v; } catch (err) { _this.defaults.errorFn(err); delete definitions[definition.name]; delete _this.s[definition.name]; throw err; } } /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { exports['default'] = eject; /** * Eject an item from the store, if it is currently in the store. * * @param resourceName The name of the resource type of the item eject. * @param id The primary key of the item to eject. * @param options Optional configuration. * @param options.notify Whether to emit the "DS.beforeEject" and "DS.afterEject" events * @param options.clearEmptyQueries Whether to remove cached findAll queries that become empty as a result of this method call. * @returns The ejected item if one was ejected. */ function eject(resourceName, id, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var item = undefined; var found = false; id = DSUtils.resolveId(definition, id); if (!definition) { throw new _this.errors.NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr('id'); } options = DSUtils._(definition, options); // find the item to eject for (var i = 0; i < resource.collection.length; i++) { if (resource.collection[i][definition.idAttribute] == id) { // jshint ignore:line item = resource.collection[i]; // remove its expiration timestamp resource.expiresHeap.remove(item); found = true; break; } } if (found) { var _ret = (function () { // lifecycle definition.beforeEject(options, item); if (options.notify) { definition.emit('DS.beforeEject', definition, item); } // find the item in any ($$injected) cached queries var toRemove = []; DSUtils.forOwn(resource.queryData, function (items, queryHash) { if (items.$$injected) { DSUtils.remove(items, item); } // optionally remove any empty queries if (!items.length && options.clearEmptyQueries) { toRemove.push(queryHash); } }); // clean up DSUtils.forEach(resource.changeHistories[id], function (changeRecord) { DSUtils.remove(resource.changeHistory, changeRecord); }); DSUtils.forEach(toRemove, function (queryHash) { delete resource.completedQueries[queryHash]; delete resource.queryData[queryHash]; }); if (DSUtils.w) { // stop observation resource.observers[id].close(); } delete resource.observers[id]; delete resource.index[id]; delete resource.previousAttributes[id]; delete resource.completedQueries[id]; delete resource.pendingQueries[id]; delete resource.changeHistories[id]; delete resource.modified[id]; delete resource.saved[id]; // remove it from the store resource.collection.splice(i, 1); // collection has been modified definition.handleChange(item); // lifecycle definition.afterEject(options, item); if (options.notify) { definition.emit('DS.afterEject', definition, item); } return { v: item }; })(); if (typeof _ret === 'object') return _ret.v; } } /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { exports['default'] = ejectAll; /** * Eject a collection of items from the store, if any items currently in the store match the given criteria. * * @param resourceName The name of the resource type of the items eject. * @param params The criteria by which to match items to eject. See http://www.js-data.io/docs/query-syntax * @param options Optional configuration. * @returns The collection of items that were ejected, if any. */ function ejectAll(resourceName, params, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; params = params || {}; if (!definition) { throw new _this.errors.NER(resourceName); } else if (!DSUtils._o(params)) { throw DSUtils._oErr('params'); } var resource = _this.s[resourceName]; var queryHash = DSUtils.toJson(params); // get items that match the criteria var items = definition.filter(params); var ids = []; if (DSUtils.isEmpty(params)) { // remove all completed queries if ejecting all items resource.completedQueries = {}; } else { // remove matching completed query, if any delete resource.completedQueries[queryHash]; } // prepare to remove matching items DSUtils.forEach(items, function (item) { if (item && item[definition.idAttribute]) { ids.push(item[definition.idAttribute]); } }); // eject each matching item DSUtils.forEach(ids, function (id) { definition.eject(id, options); }); // collection has been modified definition.handleChange(items); return items; } /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { exports['default'] = filter; /** * Return the subset of items currently in the store that match the given criteria. * * The actual filtering is delegated to DS#defaults.defaultFilter, which can be overridden by developers. * * @param resourceName The name of the resource type of the items to filter. * @param params The criteria by which to filter items. See http://www.js-data.io/docs/query-syntax * @param options Optional configuration. * @returns Matching items. */ function filter(resourceName, params, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; if (!definition) { throw new _this.errors.NER(resourceName); } else if (params && !DSUtils._o(params)) { throw DSUtils._oErr('params'); } // Protect against null params = params || {}; options = DSUtils._(definition, options); // delegate filtering to DS#defaults.defaultFilter, which can be overridden by developers. return definition.defaultFilter.call(_this, _this.s[resourceName].collection, resourceName, params, options); } /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { exports['default'] = inject; var _utils = __webpack_require__(2); var _errors = __webpack_require__(3); /** * This is a beast of a file, but it's where a significant portion of the magic happens. * * DS#inject makes up the core of how data gets into the store. */ /** * This factory function produces an observer handler function tailor-made for the current item being injected. * * The observer handler is what allows computed properties and change tracking to function. * * @param definition Resource definition produced by DS#defineResource * @param resource Resource data as internally stored by the data store * @returns {Function} Observer handler function * @private */ function makeObserverHandler(definition, resource) { var DS = this; // using "var" avoids a JSHint error var name = definition.name; /** * This will be called by observe-js when a new change record is available for the observed object * * @param added Change record for added properties * @param removed Change record for removed properties * @param changed Change record for changed properties * @param oldValueFn Function that can be used to get the previous value of a changed property * @param firstTime Whether this is the first time this function is being called for the given item. Will only be true once. */ return function _react(added, removed, changed, oldValueFn, firstTime) { var target = this; var item = undefined; // Get the previous primary key of the observed item, in-case some knucklehead changed it var innerId = oldValueFn && oldValueFn(definition.idAttribute) ? oldValueFn(definition.idAttribute) : target[definition.idAttribute]; // Ignore changes to relation links _utils['default'].forEach(definition.relationFields, function (field) { delete added[field]; delete removed[field]; delete changed[field]; }); // Detect whether there are actually any changes if (!_utils['default'].isEmpty(added) || !_utils['default'].isEmpty(removed) || !_utils['default'].isEmpty(changed) || firstTime) { item = DS.get(name, innerId); // update item and collection "modified" timestamps resource.modified[innerId] = _utils['default'].updateTimestamp(resource.modified[innerId]); if (item && definition.instanceEvents) { setTimeout(function () { item.emit('DS.change', definition, item); }, 0); } definition.handleChange(item); // Save a change record for the item 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); } } // Recompute computed properties if any computed properties depend on changed properties if (definition.computed) { item = item || DS.get(name, innerId); _utils['default'].forOwn(definition.computed, function (fn, field) { var compute = false; // check if required fields changed _utils['default'].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) { _utils['default'].compute.call(item, fn, field); } }); } 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.'); } }; } /** * A recursive function for injecting data into the store. * * @param definition Resource definition produced by DS#defineResource * @param resource Resource data as internally stored by the data store * @param attrs The data to be injected. Will be an object or an array of objects. * @param options Optional configuration. * @returns The injected data * @private */ function _inject(definition, resource, attrs, options) { var _this = this; var injected = undefined; if (_utils['default']._a(attrs)) { // have an array of objects, go ahead and inject each one individually and return the resulting array injected = []; for (var i = 0; i < attrs.length; i++) { injected.push(_inject.call(_this, definition, resource, attrs[i], options)); } } else { // create the observer handler for the data to be injected var _react = makeObserverHandler.call(_this, definition, resource); // check if "idAttribute" is a computed property var c = definition.computed; var idA = definition.idAttribute; // compute the primary key if necessary if (c && c[idA]) { (function () { var args = []; _utils['default'].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)) { // we cannot inject any object into the store that does not have a primary key! var error = new _errors['default'].R(definition.name + '.inject: "attrs" must contain the property specified by "idAttribute"!'); options.errorFn(error); throw error; } else { try { (function () { // when injecting object that contain their nested relations, this code // will recursively inject them into their proper places in the data store. // Magic! _utils['default'].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 _errors['default'].R(definition.name + ' relation is defined but the resource is not!'); } // handle injecting hasMany relations if (_utils['default']._a(toInject)) { (function () { var items = []; _utils['default'].forEach(toInject, function (toInjectItem) { if (toInjectItem !== _this.s[relationName].index[toInjectItem[relationDef.idAttribute]]) { try { var injectedItem = relationDef.inject(toInjectItem, options.orig()); if (def.foreignKey) { injectedItem[def.foreignKey] = attrs[definition.idAttribute]; } items.push(injectedItem); } catch (err) { options.errorFn(err, 'Failed to inject ' + def.type + ' relation: "' + relationName + '"!'); } } }); })(); } else { // handle injecting belongsTo and hasOne relations if (toInject !== _this.s[relationName].index[toInject[relationDef.idAttribute]]) { try { var _injected = relationDef.inject(attrs[def.localField], options.orig()); if (def.foreignKey) { _injected[def.foreignKey] = attrs[definition.idAttribute]; } } catch (err) { options.errorFn(err, 'Failed to inject ' + def.type + ' relation: "' + relationName + '"!'); } } } } }); // primary key of item being injected var id = attrs[idA]; // item being injected var item = definition.get(id); // 0 if the item is new, otherwise the previous last modified timestamp of the item var initialLastModified = item ? resource.modified[id] : 0; // item is new if (!item) { if (attrs instanceof definition[definition['class']]) { item = attrs; } else { item = new definition[definition['class']](); } // remove relation properties from the item, since those relations have been injected by now _utils['default'].forEach(definition.relationList, function (def) { delete attrs[def.localField]; }); // copy remaining properties to the injected item _utils['default'].deepMixIn(item, attrs); // add item to collection resource.collection.push(item); resource.changeHistories[id] = []; // If we're in the browser, start observation if (_utils['default'].w) { resource.observers[id] = new _this.observe.ObjectObserver(item); resource.observers[id].open(_react, item); } // index item resource.index[id] = item; // fire observation handler for the first time _react.call(item, {}, {}, {}, null, true); // save "previous" attributes of the injected item, for change diffs later resource.previousAttributes[id] = _utils['default'].copy(item, null, null, null, definition.relationFields); } else { // item is being re-injected // new properties take precedence if (options.onConflict === 'merge') { _utils['default'].deepMixIn(item, attrs); } else if (options.onConflict === 'replace') { _utils['default'].forOwn(item, function (v, k) { if (k !== definition.idAttribute) { if (!attrs.hasOwnProperty(k)) { delete item[k]; } } }); _utils['default'].forOwn(attrs, function (v, k) { if (k !== definition.idAttribute) { item[k] = v; } }); } if (definition.resetHistoryOnInject) { // clear change history for item resource.previousAttributes[id] = _utils['default'].copy(item, null, null, null, definition.relationFields); if (resource.changeHistories[id].length) { _utils['default'].forEach(resource.changeHistories[id], function (changeRecord) { _utils['default'].remove(resource.changeHistory, changeRecord); }); resource.changeHistories[id].splice(0, resource.changeHistories[id].length); } } if (_utils['default'].w) { // force observation callback to be fired if there are any changes to the item and `Object.observe` is not available resource.observers[id].deliver(); } } // update modified timestamp of item resource.modified[id] = initialLastModified && resource.modified[id] === initialLastModified ? _utils['default'].updateTimestamp(resource.modified[id]) : resource.modified[id]; // reset expiry tracking for item resource.expiresHeap.remove(item); var timestamp = new Date().getTime(); resource.expiresHeap.push({ item: item, timestamp: timestamp, expires: definition.maxAge ? timestamp + definition.maxAge : Number.MAX_VALUE }); // final injected item injected = item; })(); } catch (err) { options.errorFn(err, attrs); } } } return injected; } /** * Inject the given object or array of objects into the data store. * * @param resourceName The name of the type of resource of the data to be injected. * @param attrs Object or array of objects. Objects must contain a primary key. * @param options Optional configuration. * @param options.notify Whether to emit the "DS.beforeInject" and "DS.afterInject" events. * @returns The injected data. */ function inject(resourceName, attrs, options) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var injected = undefined; if (!definition) { throw new _errors['default'].NER(resourceName); } else if (!_utils['default']._o(attrs) && !_utils['default']._a(attrs)) { throw new _errors['default'].IA(resourceName + '.inject: "attrs" must be an object or an array!'); } options = _utils['default']._(definition, options); // lifecycle options.beforeInject(options, attrs); if (options.notify) { definition.emit('DS.beforeInject', definition, attrs); } // start the recursive injection of data injected = _inject.call(_this, definition, resource, attrs, options); // collection was modified definition.handleChange(injected); // lifecycle options.afterInject(options, injected); if (options.notify) { definition.emit('DS.afterInject', definition, injected); } return injected; } /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { exports['default'] = create; /** * Using an adapter, create a new item. * * Generally a primary key will NOT be provided in the properties hash, * because the adapter's persistence layer should be generating one. * * @param resourceName The name of the type of resource of the new item. * @param attrs Hash of properties with which to create the new item. * @param options Optional configuration. * @param options.cacheResponse Whether the newly created item as returned by the adapter should be injected into the data store. * @param options.upsert If the properties hash contains a primary key, attempt to call DS#update instead. * @param options.notify Whether to emit the "DS.beforeCreate" and "DS.afterCreate" events. * @param options.beforeValidate Lifecycle hook. * @param options.validate Lifecycle hook. * @param options.afterValidate Lifecycle hook. * @param options.beforeCreate Lifecycle hook. * @param options.afterCreate Lifecycle hook. */ function create(resourceName, attrs, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var adapter = undefined; options = options || {}; attrs = attrs || {}; var rejectionError = undefined; if (!definition) { rejectionError = new _this.errors.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); } } return new DSUtils.Promise(function (resolve, reject) { if (rejectionError) { reject(rejectionError); } else { resolve(attrs); } }) // start lifecycle .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, attrs); } adapter = _this.getAdapterName(options); return _this.adapters[adapter].create(definition, DSUtils.omit(attrs, options.omit), options); }).then(function (attrs) { return options.afterCreate.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit('DS.afterCreate', definition, attrs); } if (options.cacheResponse) { // injected created intem into the store var created = _this.inject(definition.name, attrs, options.orig()); var id = created[definition.idAttribute]; // mark item's `find` query as completed, so a subsequent `find` call for this item will resolve immediately var resource = _this.s[resourceName]; resource.completedQueries[id] = new Date().getTime(); resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); return created; } else { // just return an un-injected instance return _this.createInstance(resourceName, attrs, options); } }).then(function (item) { return DSUtils.respond(item, { adapter: adapter }, options); }); } /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { exports['default'] = destroy; /** * Using an adapter, destroy an item. * * @param resourceName The name of the type of resource of the item to destroy. * @param id The primary key of the item to destroy. * @param options Optional configuration. * @param options.eagerEject Whether to eject the item from the store before the adapter operation completes, re-injecting if the adapter operation fails. * @param options.notify Whether to emit the "DS.beforeDestroy" and "DS.afterDestroy" events. * @param options.beforeDestroy Lifecycle hook. * @param options.afterDestroy Lifecycle hook. * @returns The primary key of the destroyed item. */ function destroy(resourceName, id, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var item = undefined; var adapter = undefined; return new DSUtils.Promise(function (resolve, reject) { id = DSUtils.resolveId(definition, id); if (!definition) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr('id')); } else { // check if the item is in the store item = definition.get(id) || { id: id }; options = DSUtils._(definition, options); resolve(item); } }) // start lifecycle .then(function (attrs) { return options.beforeDestroy.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit('DS.beforeDestroy', definition, attrs); } // don't wait for the adapter, remove the item from the store if (options.eagerEject) { definition.eject(id); } adapter = definition.getAdapter(options); return adapter.destroy(definition, id, options); }).then(function () { return options.afterDestroy.call(item, options, item); }).then(function (item) { if (options.notify) { definition.emit('DS.afterDestroy', definition, item); } // make sure the item is removed from the store definition.eject(id); return DSUtils.respond(id, { adapter: adapter }, options); })['catch'](function (err) { // rollback by re-injecting the item into the store if (options && options.eagerEject && item) { definition.inject(item, { notify: false }); } return DSUtils.Promise.reject(err); }); } /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { exports['default'] = destroyAll; /** * Using an adapter, destroy an item. * * @param resourceName The name of the type of resource of the item to destroy. * @param params The criteria by which to filter items to destroy. See http://www.js-data.io/docs/query-syntax * @param options Optional configuration. * @param options.eagerEject Whether to eject the items from the store before the adapter operation completes, re-injecting if the adapter operation fails. * @param options.notify Whether to emit the "DS.beforeDestroy" and "DS.afterDestroy" events. * @param options.beforeDestroy Lifecycle hook. * @param options.afterDestroy Lifecycle hook. * @returns The ejected items, if any. */ function destroyAll(resourceName, params, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var ejected = undefined, toEject = undefined, adapter = undefined; params = params || {}; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._o(params)) { reject(DSUtils._oErr('attrs')); } else { options = DSUtils._(definition, options); resolve(); } }).then(function () { // find items that are to be ejected from the store toEject = definition.defaultFilter.call(_this, resourceName, params); return options.beforeDestroy(options, toEject); }).then(function () { if (options.notify) { definition.emit('DS.beforeDestroy', definition, toEject); } // don't wait for the adapter, remove the items from the store if (options.eagerEject) { ejected = definition.ejectAll(params); } adapter = definition.getAdapterName(options); return _this.adapters[adapter].destroyAll(definition, params, options); }).then(function () { return options.afterDestroy(options, toEject); }).then(function () { if (options.notify) { definition.emit('DS.afterDestroy', definition, toEject); } // make sure items are removed from the store return ejected || definition.ejectAll(params); }).then(function (items) { return DSUtils.respond(items, { adapter: adapter }, options); })['catch'](function (err) { // rollback by re-injecting the items into the store if (options && options.eagerEject && ejected) { definition.inject(ejected, { notify: false }); } return DSUtils.Promise.reject(err); }); } /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { exports['default'] = find; /* jshint -W082 */ /** * Using an adapter, retrieve a single item. * * @param resourceName The of the type of resource of the item to retrieve. * @param id The primary key of the item to retrieve. * @param options Optional configuration. * @param options.bypassCache Whether to ignore any cached item and force the retrieval through the adapter. * @param options.cacheResponse Whether to inject the found item into the data store. * @param options.strictCache Whether to only consider items to be "cached" if they were injected into the store as the result of `find` or `findAll`. * @param options.strategy The retrieval strategy to use. * @param options.findStrategy The retrieval strategy to use. Overrides "strategy". * @param options.fallbackAdapters Array of names of adapters to use if using "fallback" strategy. * @param options.findFallbackAdapters Array of names of adapters to use if using "fallback" strategy. Overrides "fallbackAdapters". * @returns The item. */ function find(resourceName, id, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var adapter = undefined; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr('id')); } else { options = DSUtils._(definition, options); if (options.params) { options.params = DSUtils.copy(options.params); } if (options.bypassCache || !options.cacheResponse) { delete resource.completedQueries[id]; } if ((!options.findStrictCache || id in resource.completedQueries) && definition.get(id) && !options.bypassCache) { // resolve immediately with the cached item resolve(definition.get(id)); } else { // we're going to delegate to the adapter next delete resource.completedQueries[id]; resolve(); } } }).then(function (item) { if (!item) { if (!(id in resource.pendingQueries)) { var promise = undefined; var strategy = options.findStrategy || options.strategy; // try subsequent adapters if the preceeding one fails if (strategy === 'fallback') { (function () { var makeFallbackCall = function makeFallbackCall(index) { adapter = definition.getAdapterName((options.findFallbackAdapters || options.fallbackAdapters)[index]); return _this.adapters[adapter].find(definition, id, options)['catch'](function (err) { index++; if (index < options.fallbackAdapters.length) { return makeFallbackCall(index); } else { return DSUtils.Promise.reject(err); } }); }; promise = makeFallbackCall(0); })(); } else { adapter = definition.getAdapterName(options); // just make a single attempt promise = _this.adapters[adapter].find(definition, id, options); } resource.pendingQueries[id] = promise.then(function (data) { // Query is no longer pending delete resource.pendingQueries[id]; if (options.cacheResponse) { // inject the item into the data store var injected = definition.inject(data, options.orig()); // mark the item as "cached" resource.completedQueries[id] = new Date().getTime(); resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); return injected; } else { // just return an un-injected instance return definition.createInstance(data, options.orig()); } }); } return resource.pendingQueries[id]; } else { // resolve immediately with the item return item; } }).then(function (item) { return DSUtils.respond(item, { adapter: adapter }, options); })['catch'](function (err) { if (resource) { delete resource.pendingQueries[id]; } return DSUtils.Promise.reject(err); }); } /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { exports['default'] = findAll; /* jshint -W082 */ function processResults(data, resourceName, queryHash, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; 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; // Merge the new values into the cache var injected = definition.inject(data, options.orig()); // Make sure each object is added to completedQueries if (DSUtils._a(injected)) { DSUtils.forEach(injected, function (item) { if (item) { var id = item[idAttribute]; if (id) { resource.completedQueries[id] = date; resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); } } }); } else { options.errorFn('response is expected to be an array!'); resource.completedQueries[injected[idAttribute]] = date; } return injected; } /** * Using an adapter, retrieve a collection of items. * * @param resourceName The name of the type of resource of the items to retrieve. * @param params The criteria by which to filter items to retrieve. See http://www.js-data.io/docs/query-syntax * @param options Optional configuration. * @param options.bypassCache Whether to ignore any cached query for these items and force the retrieval through the adapter. * @param options.cacheResponse Whether to inject the found items into the data store. * @returns The items. */ function findAll(resourceName, params, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var queryHash = undefined, adapter = undefined; return new DSUtils.Promise(function (resolve, reject) { params = params || {}; if (!_this.defs[resourceName]) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._o(params)) { reject(DSUtils._oErr('params')); } else { options = DSUtils._(definition, options); queryHash = DSUtils.toJson(params); if (options.params) { options.params = DSUtils.copy(options.params); } // force a new request if (options.bypassCache || !options.cacheResponse) { delete resource.completedQueries[queryHash]; delete resource.queryData[queryHash]; } if (queryHash in resource.completedQueries) { if (options.useFilter) { // resolve immediately by filtering data from the data store resolve(definition.filter(params, options.orig())); } else { // resolve immediately by returning the cached array from the previously made query resolve(resource.queryData[queryHash]); } } else { resolve(); } } }).then(function (items) { if (!(queryHash in resource.completedQueries)) { if (!(queryHash in resource.pendingQueries)) { var promise = undefined; var strategy = options.findAllStrategy || options.strategy; // try subsequent adapters if the preceeding one fails if (strategy === 'fallback') { (function () { var makeFallbackCall = function makeFallbackCall(index) { adapter = definition.getAdapterName((options.findAllFallbackAdapters || options.fallbackAdapters)[index]); return _this.adapters[adapter].findAll(definition, params, options)['catch'](function (err) { index++; if (index < options.fallbackAdapters.length) { return makeFallbackCall(index); } else { return DSUtils.Promise.reject(err); } }); }; promise = makeFallbackCall(0); })(); } else { adapter = definition.getAdapterName(options); // just make a single attempt promise = _this.adapters[adapter].findAll(definition, params, options); } resource.pendingQueries[queryHash] = promise.then(function (data) { // Query is no longer pending delete resource.pendingQueries[queryHash]; if (options.cacheResponse) { // inject the items into the data store 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] = definition.createInstance(item, options.orig()); }); return data; } }); } return resource.pendingQueries[queryHash]; } else { // resolve immediately with the items return items; } }).then(function (items) { return DSUtils.respond(items, { adapter: adapter }, options); })['catch'](function (err) { if (resource) { delete resource.pendingQueries[queryHash]; } return DSUtils.Promise.reject(err); }); } /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { exports['default'] = loadRelations; 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; } /** * Load the specified relations for the given instance. * * @param resourceName The name of the type of resource of the instance for which to load relations. * @param instance The instance or the primary key of the instance. * @param relations An array of the relations to load. * @param options Optional configuration. * @returns The instance, now with its relations loaded. */ function loadRelations(resourceName, instance, relations, options) { var _this = this; var DSUtils = _this.utils; var DSErrors = _this.errors; var definition = _this.defs[resourceName]; return new DSUtils.Promise(function (resolve, reject) { if (DSUtils._sn(instance)) { instance = definition.get(instance); } if (DSUtils._s(relations)) { relations = [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 { (function () { var _options = DSUtils._(definition, options); var tasks = []; DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; var relationDef = definition.getResource(relationName); var __options = DSUtils._(relationDef, options); // relations can be loaded based on resource name or field name if (!relations.length || DSUtils.contains(relations, relationName) || DSUtils.contains(relations, def.localField)) { var task = undefined; 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') { if (def.localKeys) { delete params[def.foreignKey]; params.where = _defineProperty({}, relationDef.idAttribute, { 'in': instance[def.localKeys] }); } task = relationDef.findAll(params, __options.orig()); } else if (def.type === 'hasOne') { if (def.localKey && instance[def.localKey]) { task = relationDef.find(instance[def.localKey], __options.orig()); } else if (def.foreignKey) { task = relationDef.findAll(params, __options.orig()).then(function (hasOnes) { return hasOnes.length ? hasOnes[0] : null; }); } } else if (instance[def.localKey]) { task = relationDef.find(instance[def.localKey], __options.orig()); } if (task) { tasks.push(task); } } }); resolve(tasks); })(); } }).then(function (tasks) { return DSUtils.Promise.all(tasks); }).then(function () { return instance; }); } /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { exports['default'] = reap; /** * Find expired items of the specified resource type and perform the configured action. * * @param resourceName The name of the type of resource of the items to reap. * @param options Optional configuration. * @returns The reaped items. */ function reap(resourceName, options) { var _this = this; var DSUtils = _this.utils; 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; } var items = []; var now = new Date().getTime(); var expiredItem = undefined; // find the expired items while ((expiredItem = resource.expiresHeap.peek()) && expiredItem.expires < now) { items.push(expiredItem.item); delete expiredItem.item; resource.expiresHeap.pop(); } resolve(items); } }).then(function (items) { // only hit lifecycle if there are items if (items.length) { definition.beforeReap(options, items); if (options.notify) { definition.emit('DS.beforeReap', definition, items); } } if (options.reapAction === 'inject') { (function () { var timestamp = new Date().getTime(); DSUtils.forEach(items, function (item) { resource.expiresHeap.push({ item: item, timestamp: timestamp, expires: definition.maxAge ? timestamp + definition.maxAge : Number.MAX_VALUE }); }); })(); } else if (options.reapAction === 'eject') { DSUtils.forEach(items, function (item) { definition.eject(item[definition.idAttribute]); }); } else if (options.reapAction === 'refresh') { var _ret2 = (function () { var tasks = []; DSUtils.forEach(items, function (item) { tasks.push(definition.refresh(item[definition.idAttribute])); }); return { v: DSUtils.Promise.all(tasks) }; })(); if (typeof _ret2 === 'object') return _ret2.v; } return items; }).then(function (items) { // only hit lifecycle if there are items if (items.length) { definition.afterReap(options, items); if (options.notify) { definition.emit('DS.afterReap', definition, items); } } return items; }); } /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { exports['default'] = save; /** * Save a single item in its present state. * * @param resourceName The name of the type of resource of the item. * @param id The primary key of the item. * @param options Optional congifuration. * @returns The item, now saved. */ function save(resourceName, id, options) { var _this = this; var DSUtils = _this.utils; var DSErrors = _this.errors; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var item = undefined, noChanges = undefined, adapter = undefined; 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 (!definition.get(id)) { reject(new DSErrors.R('id "' + id + '" not found in cache!')); } else { item = definition.get(id); options = DSUtils._(definition, options); resolve(item); } }) // start lifecycle .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, attrs); } // only send changed properties to the adapter if (options.changesOnly) { if (DSUtils.w) { resource.observers[id].deliver(); } var toKeep = []; var changes = definition.changes(id); for (var key in changes.added) { toKeep.push(key); } for (key in changes.changed) { toKeep.push(key); } changes = DSUtils.pick(attrs, toKeep); // no changes? no save if (DSUtils.isEmpty(changes)) { // no changes, return noChanges = true; return attrs; } else { attrs = changes; } } adapter = definition.getAdapterName(options); return _this.adapters[adapter].update(definition, id, DSUtils.omit(attrs, options.omit), options); }).then(function (data) { return options.afterUpdate.call(data, options, data); }).then(function (attrs) { if (options.notify) { definition.emit('DS.afterUpdate', definition, attrs); } if (noChanges) { // no changes, just return return attrs; } else if (options.cacheResponse) { // inject the reponse into the store, updating the item var injected = definition.inject(attrs, options.orig()); var _id = injected[definition.idAttribute]; // mark the item as "saved" resource.saved[_id] = DSUtils.updateTimestamp(resource.saved[_id]); if (!definition.resetHistoryOnInject) { resource.previousAttributes[_id] = DSUtils.copy(injected, null, null, null, definition.relationFields); } return injected; } else { // just return an instance return definition.createInstance(attrs, options.orig()); } }).then(function (item) { return DSUtils.respond(item, { adapter: adapter }, options); }); } /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { exports['default'] = update; /** * Update a single item using the supplied properties hash. * * @param resourceName The name of the type of resource of the item to update. * @param id The primary key of the item to update. * @param attrs The attributes with which to update the item. * @param options Optional configuration. * @returns The item, now updated. */ function update(resourceName, id, attrs, options) { var _this = this; var DSUtils = _this.utils; var DSErrors = _this.errors; var definition = _this.defs[resourceName]; var adapter = undefined; 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); resolve(attrs); } }) // start lifecycle .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, attrs); } adapter = definition.getAdapterName(options); return _this.adapters[adapter].update(definition, id, DSUtils.omit(attrs, options.omit), options); }).then(function (data) { return options.afterUpdate.call(data, options, data); }).then(function (attrs) { if (options.notify) { definition.emit('DS.afterUpdate', definition, attrs); } if (options.cacheResponse) { // inject the updated item into the store var injected = definition.inject(attrs, options.orig()); var resource = _this.s[resourceName]; var _id = injected[definition.idAttribute]; // mark the item as "saved" resource.saved[_id] = DSUtils.updateTimestamp(resource.saved[_id]); if (!definition.resetHistoryOnInject) { resource.previousAttributes[_id] = DSUtils.copy(injected, null, null, null, definition.relationFields); } return injected; } else { // just return an instance return definition.createInstance(attrs, options.orig()); } }).then(function (item) { return DSUtils.respond(item, { adapter: adapter }, options); }); } /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { exports['default'] = updateAll; /** * Update a collection of items using the supplied properties hash. * * @param resourceName The name of the type of resource of the items to update. * @param attrs The attributes with which to update the item. * @param params The criteria by which to select items to update. See http://www.js-data.io/docs/query-syntax * @param options Optional configuration. * @returns The updated items. */ function updateAll(resourceName, attrs, params, options) { var _this = this; var DSUtils = _this.utils; var DSErrors = _this.errors; var definition = _this.defs[resourceName]; var adapter = undefined; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new DSErrors.NER(resourceName)); } else { options = DSUtils._(definition, options); resolve(attrs); } }) // start lifecycle .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, attrs); } adapter = definition.getAdapterName(options); return _this.adapters[adapter].updateAll(definition, DSUtils.omit(attrs, options.omit), params, options); }).then(function (data) { return options.afterUpdate.call(data, options, data); }).then(function (data) { if (options.notify) { definition.emit('DS.afterUpdate', definition, attrs); } var origOptions = options.orig(); if (options.cacheResponse) { var _ret = (function () { // inject the updated items into the store var injected = definition.inject(data, origOptions); var resource = _this.s[resourceName]; // mark the items as "saved" DSUtils.forEach(injected, function (i) { var id = i[definition.idAttribute]; resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); if (!definition.resetHistoryOnInject) { resource.previousAttributes[id] = DSUtils.copy(i, null, null, null, definition.relationFields); } }); return { v: injected }; })(); if (typeof _ret === 'object') return _ret.v; } else { var _ret2 = (function () { // just return instances var instances = []; DSUtils.forEach(data, function (item) { instances.push(definition.createInstance(item, origOptions)); }); return { v: instances }; })(); if (typeof _ret2 === 'object') return _ret2.v; } }).then(function (items) { return DSUtils.respond(items, { adapter: adapter }, options); }); } /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(26); /** * 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; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(26); // 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; /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(26); /** * "Safer" String.toLowerCase() */ function lowerCase(str){ str = toString(str); return str.toLowerCase(); } module.exports = lowerCase; /***/ } /******/ ]) });
packages/material-ui-icons/src/AddAPhoto.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M3 4V1h2v3h3v2H5v3H3V6H0V4h3zm3 6V7h3V4h7l1.83 2H21c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H5c-1.1 0-2-.9-2-2V10h3zm7 9c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-3.2-5c0 1.77 1.43 3.2 3.2 3.2s3.2-1.43 3.2-3.2-1.43-3.2-3.2-3.2-3.2 1.43-3.2 3.2z" /></g> , 'AddAPhoto');
src/Tabs/TabTemplate.spec.js
frnk94/material-ui
/* eslint-env mocha */ import React from 'react'; import {shallow} from 'enzyme'; import {assert} from 'chai'; import TabTemplate from './TabTemplate'; import getMuiTheme from '../styles/getMuiTheme'; describe('<TabTemplate />', () => { const muiTheme = getMuiTheme(); const shallowWithContext = (node) => shallow(node, {context: {muiTheme}}); it('should have different tab template style', () => { const wrapper = shallowWithContext( <TabTemplate style={{backgroundColor: 'red'}} selected={true} /> ); assert.strictEqual(wrapper.props().style.backgroundColor, 'red', 'should have backgroundColor equal to red'); }); });
src/entypo/Popup.js
cox-auto-kc/react-entypo
import React from 'react'; import EntypoIcon from '../EntypoIcon'; const iconClass = 'entypo-svgicon entypo--Popup'; let EntypoPopup = (props) => ( <EntypoIcon propClass={iconClass} {...props}> <path d="M16,2H7.979C6.88,2,6,2.88,6,3.98V12c0,1.1,0.9,2,2,2h8c1.1,0,2-0.9,2-2V4C18,2.9,17.1,2,16,2z M16,12H8V4h8V12z M4,10H2v6c0,1.1,0.9,2,2,2h6v-2H4V10z"/> </EntypoIcon> ); export default EntypoPopup;
demo/components/select/SelectDemo.js
ctco/rosemary-ui
import React from 'react'; import {Select} from '../../../src'; import DemoWithSnippet from '../../layout/DemoWithSnippet'; export default class SelectDemo extends React.Component { constructor(props) { super(props); this.options = [ {id: 1, displayString: 'Option 1'}, {id: 2, displayString: 'Option 2'}, {id: 3, displayString: 'Option 3'}, {id: 4, displayString: 'Option 4'}, {id: 5, displayString: 'Option 5', grayed_item: true}, {id: 6, displayString: 'Option 6', grayed_item: false}, {id: 7, displayString: 'Option 7'}, {id: 8, displayString: 'Option 8'}, {id: 9, displayString: 'Option 9'}, {id: 10, displayString: 'Option 10', grayed_item: true}, {id: 11, displayString: 'Option 11'} ]; this.state = { value: 10, open: false }; } handleChange(item) { if (item === 3) { this.setState({ open: false }); } } render() { return ( <div> <h2> Variations </h2> <DemoWithSnippet> <Select className="select--sm" placeholder="Small" options={this.options}/> <br/><br/> <Select placeholder="Default" options={this.options}/> <br/><br/> <Select className="select--lg" placeholder="Large" options={this.options}/> </DemoWithSnippet> <div className="separator-block"></div> <h2> Can be rendered with a placeholder </h2> <DemoWithSnippet> <Select placeholder="Please select..." options={this.options}/> </DemoWithSnippet> <div className="separator-block"></div> <h2> Can be controlled </h2> <DemoWithSnippet> <Select placeholder="Please select..." onChange={(value) => this.setState({value})} value={this.state.value} options={this.options} /> </DemoWithSnippet> <div className="separator-block"></div> <h2> Can be with search </h2> <DemoWithSnippet> <Select className="select--sm" placeholder="Small" options={this.options} search={true}/> </DemoWithSnippet> <h2> Can be Controllable(will close when option 3 are selected) </h2> <DemoWithSnippet> <Select className="select--sm" onPopupStateChange={(open) => { this.setState({open}); }} open={this.state.open} onChange={(item) => this.handleChange(item)} options={this.options} search={true}/> </DemoWithSnippet> </div> ); } }
src/browser/ui/dom/DOMProperty.js
ropik/react
/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMProperty * @typechecks static-only */ /*jslint bitwise: true */ 'use strict'; var invariant = require('invariant'); function checkMask(value, bitmask) { return (value & bitmask) === bitmask; } var DOMPropertyInjection = { /** * Mapping from normalized, camelcased property names to a configuration that * specifies how the associated DOM property should be accessed or rendered. */ MUST_USE_ATTRIBUTE: 0x1, MUST_USE_PROPERTY: 0x2, HAS_SIDE_EFFECTS: 0x4, HAS_BOOLEAN_VALUE: 0x8, HAS_NUMERIC_VALUE: 0x10, HAS_POSITIVE_NUMERIC_VALUE: 0x20 | 0x10, HAS_OVERLOADED_BOOLEAN_VALUE: 0x40, /** * Inject some specialized knowledge about the DOM. This takes a config object * with the following properties: * * isCustomAttribute: function that given an attribute name will return true * if it can be inserted into the DOM verbatim. Useful for data-* or aria-* * attributes where it's impossible to enumerate all of the possible * attribute names, * * Properties: object mapping DOM property name to one of the * DOMPropertyInjection constants or null. If your attribute isn't in here, * it won't get written to the DOM. * * DOMAttributeNames: object mapping React attribute name to the DOM * attribute name. Attribute names not specified use the **lowercase** * normalized name. * * DOMPropertyNames: similar to DOMAttributeNames but for DOM properties. * Property names not specified use the normalized name. * * DOMMutationMethods: Properties that require special mutation methods. If * `value` is undefined, the mutation method should unset the property. * * @param {object} domPropertyConfig the config as described above. */ injectDOMPropertyConfig: function(domPropertyConfig) { var Properties = domPropertyConfig.Properties || {}; var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {}; var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {}; var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {}; if (domPropertyConfig.isCustomAttribute) { DOMProperty._isCustomAttributeFunctions.push( domPropertyConfig.isCustomAttribute ); } for (var propName in Properties) { invariant( !DOMProperty.isStandardName.hasOwnProperty(propName), 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property ' + '\'%s\' which has already been injected. You may be accidentally ' + 'injecting the same DOM property config twice, or you may be ' + 'injecting two configs that have conflicting property names.', propName ); DOMProperty.isStandardName[propName] = true; var lowerCased = propName.toLowerCase(); DOMProperty.getPossibleStandardName[lowerCased] = propName; if (DOMAttributeNames.hasOwnProperty(propName)) { var attributeName = DOMAttributeNames[propName]; DOMProperty.getPossibleStandardName[attributeName] = propName; DOMProperty.getAttributeName[propName] = attributeName; } else { DOMProperty.getAttributeName[propName] = lowerCased; } DOMProperty.getPropertyName[propName] = DOMPropertyNames.hasOwnProperty(propName) ? DOMPropertyNames[propName] : propName; if (DOMMutationMethods.hasOwnProperty(propName)) { DOMProperty.getMutationMethod[propName] = DOMMutationMethods[propName]; } else { DOMProperty.getMutationMethod[propName] = null; } var propConfig = Properties[propName]; DOMProperty.mustUseAttribute[propName] = checkMask(propConfig, DOMPropertyInjection.MUST_USE_ATTRIBUTE); DOMProperty.mustUseProperty[propName] = checkMask(propConfig, DOMPropertyInjection.MUST_USE_PROPERTY); DOMProperty.hasSideEffects[propName] = checkMask(propConfig, DOMPropertyInjection.HAS_SIDE_EFFECTS); DOMProperty.hasBooleanValue[propName] = checkMask(propConfig, DOMPropertyInjection.HAS_BOOLEAN_VALUE); DOMProperty.hasNumericValue[propName] = checkMask(propConfig, DOMPropertyInjection.HAS_NUMERIC_VALUE); DOMProperty.hasPositiveNumericValue[propName] = checkMask(propConfig, DOMPropertyInjection.HAS_POSITIVE_NUMERIC_VALUE); DOMProperty.hasOverloadedBooleanValue[propName] = checkMask(propConfig, DOMPropertyInjection.HAS_OVERLOADED_BOOLEAN_VALUE); invariant( !DOMProperty.mustUseAttribute[propName] || !DOMProperty.mustUseProperty[propName], 'DOMProperty: Cannot require using both attribute and property: %s', propName ); invariant( DOMProperty.mustUseProperty[propName] || !DOMProperty.hasSideEffects[propName], 'DOMProperty: Properties that have side effects must use property: %s', propName ); invariant( !!DOMProperty.hasBooleanValue[propName] + !!DOMProperty.hasNumericValue[propName] + !!DOMProperty.hasOverloadedBooleanValue[propName] <= 1, 'DOMProperty: Value can be one of boolean, overloaded boolean, or ' + 'numeric value, but not a combination: %s', propName ); } } }; var defaultValueCache = {}; /** * DOMProperty exports lookup objects that can be used like functions: * * > DOMProperty.isValid['id'] * true * > DOMProperty.isValid['foobar'] * undefined * * Although this may be confusing, it performs better in general. * * @see http://jsperf.com/key-exists * @see http://jsperf.com/key-missing */ var DOMProperty = { ID_ATTRIBUTE_NAME: 'data-reactid', /** * Checks whether a property name is a standard property. * @type {Object} */ isStandardName: {}, /** * Mapping from lowercase property names to the properly cased version, used * to warn in the case of missing properties. * @type {Object} */ getPossibleStandardName: {}, /** * Mapping from normalized names to attribute names that differ. Attribute * names are used when rendering markup or with `*Attribute()`. * @type {Object} */ getAttributeName: {}, /** * Mapping from normalized names to properties on DOM node instances. * (This includes properties that mutate due to external factors.) * @type {Object} */ getPropertyName: {}, /** * Mapping from normalized names to mutation methods. This will only exist if * mutation cannot be set simply by the property or `setAttribute()`. * @type {Object} */ getMutationMethod: {}, /** * Whether the property must be accessed and mutated as an object property. * @type {Object} */ mustUseAttribute: {}, /** * Whether the property must be accessed and mutated using `*Attribute()`. * (This includes anything that fails `<propName> in <element>`.) * @type {Object} */ mustUseProperty: {}, /** * Whether or not setting a value causes side effects such as triggering * resources to be loaded or text selection changes. We must ensure that * the value is only set if it has changed. * @type {Object} */ hasSideEffects: {}, /** * Whether the property should be removed when set to a falsey value. * @type {Object} */ hasBooleanValue: {}, /** * Whether the property must be numeric or parse as a * numeric and should be removed when set to a falsey value. * @type {Object} */ hasNumericValue: {}, /** * Whether the property must be positive numeric or parse as a positive * numeric and should be removed when set to a falsey value. * @type {Object} */ hasPositiveNumericValue: {}, /** * Whether the property can be used as a flag as well as with a value. Removed * when strictly equal to false; present without a value when strictly equal * to true; present with a value otherwise. * @type {Object} */ hasOverloadedBooleanValue: {}, /** * All of the isCustomAttribute() functions that have been injected. */ _isCustomAttributeFunctions: [], /** * Checks whether a property name is a custom attribute. * @method */ isCustomAttribute: function(attributeName) { for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) { var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i]; if (isCustomAttributeFn(attributeName)) { return true; } } return false; }, /** * Returns the default property value for a DOM property (i.e., not an * attribute). Most default values are '' or false, but not all. Worse yet, * some (in particular, `type`) vary depending on the type of element. * * TODO: Is it better to grab all the possible properties when creating an * element to avoid having to create the same element twice? */ getDefaultValueForProperty: function(nodeName, prop) { var nodeDefaults = defaultValueCache[nodeName]; var testElement; if (!nodeDefaults) { defaultValueCache[nodeName] = nodeDefaults = {}; } if (!(prop in nodeDefaults)) { testElement = document.createElement(nodeName); nodeDefaults[prop] = testElement[prop]; } return nodeDefaults[prop]; }, injection: DOMPropertyInjection }; module.exports = DOMProperty;
website/Home.js
sahat/megaboilerplate
import haikunate from 'haikunator'; import React from 'react'; import Header from './Header'; import Footer from './Footer'; import Platform from './sections/Platform'; import StaticSiteGenerator from './sections/StaticSiteGenerator'; import JsLibrary from './sections/JsLibrary'; import Framework from './sections/Framework'; import TemplateEngine from './sections/TemplateEngine'; import CssFramework from './sections/CssFramework'; import CssPreprocessor from './sections/CssPreprocessor'; import BuildTool from './sections/BuildTool'; import Testing from './sections/Testing' import Database from './sections/Database'; import Authentication from './sections/Authentication'; import JsFramework from './sections/JsFramework'; import Deployment from './sections/Deployment'; import NextSteps from './sections/NextSteps'; import { VelocityComponent } from 'velocity-react'; class Home extends React.Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.handleGenerateLibraryName = this.handleGenerateLibraryName.bind(this); this.handleDisableAutoScroll = this.handleDisableAutoScroll.bind(this); this.clickDownload = this.clickDownload.bind(this); this.state = {}; } componentDidMount() { // require it here to avoid "window is not defined" error during server-side rendering const swal = require('sweetalert'); try { const disableAutoScroll = localStorage.getItem('disableAutoScroll'); this.setState({ beginner: false, disableAutoScroll: disableAutoScroll === 'true', copyClipboardText: 'Copy to clipboard', isDownloadLoading: false }); } catch (e) { console.warn(e); } } clickDownload(options = {}) { const state = this.state; if (!state.platform) { console.info('Please select a platform.'); return this.setState({ platformValidationError: 'Please select a platform.', generateDownloadLinkInProgress: false }); } else if (state.platform === 'html5' && !state.staticSiteGenerator) { console.info('Please select a static site generator.'); return this.setState({ staticSiteGeneratorValidationError: 'Please select a static site generator.', generateDownloadLinkInProgress: false }); } else if (state.platform === 'library' && !state.jsLibraryName) { console.info('Please enter a library name.'); return this.setState({ jsLibraryValidationError: 'Please enter a library name.', generateDownloadLinkInProgress: false }); } else if (state.platform === 'node' && !state.framework) { console.info('Please select a framework.'); return this.setState({ frameworkValidationError: 'Please select a framework.', generateDownloadLinkInProgress: false }); } else if (state.platform === 'node' && !state.cssFramework) { console.info('Please select a CSS framework.'); return this.setState({ cssFrameworkValidationError: 'Please select a CSS framework.', generateDownloadLinkInProgress: false }); } else if (state.platform === 'node' && !state.cssPreprocessor) { console.info('Please select a CSS preprocessor.'); return this.setState({ cssPreprocessorValidationError: 'Please select a CSS preprocessor.', generateDownloadLinkInProgress: false }); } else if (state.platform === 'node' && !state.jsFramework) { console.info('Please make a selection.'); return this.setState({ jsFrameworkValidationError: 'Please make a selection.', generateDownloadLinkInProgress: false }); } else if (state.platform === 'node' && !state.templateEngine && state.jsFramework !== 'angularjs') { console.info('Please select a template engine.'); return this.setState({ templateEngineValidationError: 'Please select a template engine.', generateDownloadLinkInProgress: false }); } else if (state.platform === 'node' && state.jsFramework !== 'none' && !state.buildTool) { console.info('Please select a build tool.'); return this.setState({ buildToolValidationError: 'Please select a build tool.', generateDownloadLinkInProgress: false }); } else if (state.platform === 'node' && !state.testing) { console.info('Please select a testing framework.'); return this.setState({ testingValidationError: 'Please select a testing framework.', generateDownloadLinkInProgress: false }); } else if (state.platform === 'node' && !state.database) { console.info('Please select a database.'); return this.setState({ databaseValidationError: 'Please select a database.', generateDownloadLinkInProgress: false }); } else if (state.platform === 'node' && !state.authentication && state.database !== 'none') { console.info('Please check all that apply.'); return this.setState({ authenticationValidationError: 'Please check all that apply.', generateDownloadLinkInProgress: false }); } // Show download button spinner if (!options.generateDownloadLink) { this.setState({ isDownloadLoading: true }); } // Show next steps component this.setState({ showNextSteps: true }); if (!state.disableAutoScroll) { if (options.generateDownloadLink) { $(this.refs.download).velocity('scroll'); } else { $(this.refs.nextSteps).velocity('scroll'); } } const data = Object.assign({}, state); data.appName = haikunate({ tokenLength: 0 }); if (data.jsFramework === 'none') { data.jsFramework = null; } if (options.generateDownloadLink) { data.generateDownloadLink = true; } // Convert ES6 set to array data.authentication = data.authentication ? Array.from(data.authentication) : []; data.frameworkOptions = data.frameworkOptions ? Array.from(data.frameworkOptions) : []; data.cssPreprocessorOptions = data.cssPreprocessorOptions ? Array.from(data.cssPreprocessorOptions) : []; data.reactOptions = data.reactOptions ? Array.from(data.reactOptions) : []; data.jsLibraryOptions = data.jsLibraryOptions ? Array.from(data.jsLibraryOptions) : []; ga('send', 'event', 'Mega Boilerplate', 'Download', 'Downloads'); if (options.generateDownloadLink) { ga('send', 'event', 'Mega Boilerplate', 'Download', 'Generated Links'); $.ajax({ url: '/download', method: 'POST', contentType: 'application/json; charset=utf-8', data: JSON.stringify(data) }).done((response, status, request) => { this.setState({ downloadLinkInputValue: response.link, generateDownloadLinkSuccess: true, generateDownloadLinkInProgress: false }); $(this.refs.downloadLinkInput).focus(); }).fail((jqXHR) => { this.setState({ generateDownloadLinkSuccess: false, generateDownloadLinkInProgress: false }); const title = encodeURIComponent(jqXHR.responseJSON.message); const body = encodeURIComponent('\n##### :boom: Error Stack Trace\n' + '\`\`\`js\n' + jqXHR.responseJSON.stack + '\n\`\`\`'); swal({ title: 'Server Error', text: `${jqXHR.responseJSON.message}<br><strong><a href='https://github.com/sahat/megaboilerplate/issues/new?title=${title}&body=${body}' target="_blank">Report a bug</a></strong>`, type: 'error', html: true }); }); } else { $.ajax({ url: '/download', method: 'POST', contentType: 'application/json; charset=utf-8', data: JSON.stringify(data) }).done((response, status, request) => { const disp = request.getResponseHeader('Content-Disposition'); if (disp && disp.search('attachment') !== -1) { this.setState({ isDownloadLoading: false }); const form = $('<form method="POST" action="/download">'); $.each(data, (k, v) => { if (v) { form.append($(`<input type="hidden" name="${k}" value="${v}">`)); } }); $('body').append(form); form.submit(); } }).fail((jqXHR) => { const title = encodeURIComponent(jqXHR.responseJSON.message); const body = encodeURIComponent('\n##### :boom: Error Stack Trace\n' + '\`\`\`js\n' + jqXHR.responseJSON.stack + '\n\`\`\`'); swal({ title: 'Server Error', text: `${jqXHR.responseJSON.message}<br><strong><a href='https://github.com/sahat/megaboilerplate/issues/new?title=${title}&body=${body}' target="_blank">Report a bug</a></strong>`, type: 'error', html: true }); this.setState({ isDownloadLoading: false }); }); } } handleGenerateLibraryName() { const newState = Object.assign({}, this.state); newState.jsLibraryName = haikunate({ tokenLength: 0 }); newState.jsLibraryValidationError = null; this.setState(newState); } handleChange(event) { const name = event.target.name; const value = event.target.value; const isChecked = event.target.checked; const state = Object.assign({}, this.state); const refs = this.refs; switch (name) { case 'beginner': state.beginner = isChecked; if (isChecked) { ga('send', 'event', 'Mega Boilerplate', 'Site Options', 'Beginner'); } break; case 'platformRadios': const whitelist = ['beginner', 'disableAutoScroll', 'copyClipboardText', 'isDownloadLoading']; for (const key in state) { if (state.hasOwnProperty(key)) { if (whitelist.indexOf(key) === -1) { state[key] = null; } } } ga('send', 'event', 'Mega Boilerplate', 'Platform', value); state.platform = value; if (!state.disableAutoScroll) { $(refs.platform).velocity('scroll'); } state.platformValidationError = null; break; case 'staticSiteGeneratorRadios': if (!state.staticSiteGenerator && !state.disableAutoScroll) { $(refs.staticSiteGenerator).velocity('scroll'); } ga('send', 'event', 'Mega Boilerplate', 'Static Site', value); state.staticSiteGenerator = value; state.staticSiteGeneratorValidationError = null; break; case 'jsLibraryOptionsCheckboxes': state.jsLibraryOptions = state.jsLibraryOptions || new Set(); if (isChecked) { state.jsLibraryOptions.add(value); ga('send', 'event', 'Mega Boilerplate', 'JS Library', value); } else { state.jsLibraryOptions.delete(value); } break; case 'jsLibraryName': state.jsLibraryName = value; state.jsLibraryValidationError = null; break; case 'jsLibraryAuthor': state.jsLibraryAuthor = value; break; case 'jsLibraryGithubUsername': state.jsLibraryGithubUsername = value; break; case 'jsLibraryLicenseRadios': state.jsLibraryLicense = value; ga('send', 'event', 'Mega Boilerplate', 'JS Library', value); break; case 'frameworkRadios': if (!state.framework && !state.disableAutoScroll) { $(refs.framework).velocity('scroll'); } ga('send', 'event', 'Mega Boilerplate', 'Framework', value); state.framework = value; state.frameworkValidationError = null; break; case 'frameworkOptionsCheckboxes': state.frameworkOptions = state.frameworkOptions || new Set(); if (isChecked) { state.frameworkOptions.add(value); ga('send', 'event', 'Mega Boilerplate', 'Framework', value); } else { state.frameworkOptions.delete(value); } break; case 'templateEngineRadios': if (!state.templateEngine && !state.disableAutoScroll) { $(refs.templateEngine).velocity('scroll'); } ga('send', 'event', 'Mega Boilerplate', 'Template Engine', value); state.templateEngine = value; state.templateEngineValidationError = null; break; case 'cssFrameworkRadios': if (!state.cssFramework && !state.disableAutoScroll) { $(refs.cssFramework).velocity('scroll'); } if (state.cssPreprocessor) { state.cssPreprocessor = null; } ga('send', 'event', 'Mega Boilerplate', 'CSS Framework', value); state.cssFramework = value; state.cssFrameworkValidationError = null; break; case 'cssPreprocessorRadios': if (!state.cssPreprocessor && !state.disableAutoScroll) { $(refs.cssPreprocessor).velocity('scroll'); } ga('send', 'event', 'Mega Boilerplate', 'CSS Preprocessor', value); state.cssPreprocessor = value; state.cssPreprocessorValidationError = null; state.buildTool = null; break; case 'cssPreprocessorOptionsCheckboxes': state.cssPreprocessorOptions = state.cssPreprocessorOptions || new Set(); if (isChecked) { state.cssPreprocessorOptions.add(value); ga('send', 'event', 'Mega Boilerplate', 'CSS Preprocessor', value); } else { state.cssPreprocessorOptions.delete(value); } break; case 'jsFrameworkRadios': if (!state.jsFramework && !state.disableAutoScroll) { $(refs.jsFramework).velocity('scroll'); } ga('send', 'event', 'Mega Boilerplate', 'JS Framework', value); state.jsFramework = value; state.jsFrameworkValidationError = null; state.testing = null; state.buildTool = null; break; case 'reactOptionsCheckboxes': state.reactOptions = state.reactOptions || new Set(); if (isChecked) { state.reactOptions.add(value); ga('send', 'event', 'Mega Boilerplate', 'JS Framework', value); } else { state.reactOptions.delete(value); } break; case 'buildToolRadios': if (!state.buildTool && !state.disableAutoScroll) { $(refs.buildTool).velocity('scroll'); } ga('send', 'event', 'Mega Boilerplate', 'Build Tool', value); state.buildTool = value; state.buildToolValidationError = null; break; case 'testingRadios': if (!state.testing && !state.disableAutoScroll) { $(refs.testing).velocity('scroll'); } ga('send', 'event', 'Mega Boilerplate', 'Testing', value); state.testing = value; state.testingValidationError = null; break; case 'databaseRadios': if (!state.database && !state.disableAutoScroll) { $(refs.database).velocity('scroll'); } if (value === 'none' && state.authentication) { state.authentication.clear(); } ga('send', 'event', 'Mega Boilerplate', 'Database', value); state.database = value; state.authenticationValidationError = null; state.databaseValidationError = null; break; case 'authenticationCheckboxes': state.authentication = state.authentication || new Set(); const requiresEmail = ( state.authentication.has('facebook') || state.authentication.has('google') || state.authentication.has('twitter') || state.authentication.has('github') ); if (isChecked) { ga('send', 'event', 'Mega Boilerplate', 'Authentication', value); if (value === 'none') { state.authentication.clear(); } else { state.authentication.add(value); if (value === 'facebook' || value === 'google' || value === 'twitter' || value === 'github') { state.authentication.add('email'); } } state.authenticationValidationError = null; } else { if (value === 'email' && requiresEmail) { return; } state.authentication.delete(value); } break; case 'deploymentRadios': if (!state.deployment && !state.disableAutoScroll) { $(refs.deployment).velocity('scroll'); } ga('send', 'event', 'Mega Boilerplate', 'Deployment', value); state.deployment = value; break; default: // Handle default case } // reset download link state state.generateDownloadLinkSuccess = false; this.setState(state); } handleDisableAutoScroll(event) { if (event.target.checked) { ga('send', 'event', 'Mega Boilerplate', 'Site Options', 'Disable Auto-Scroll'); } this.setState({ disableAutoScroll: event.target.checked }); try { localStorage.setItem('disableAutoScroll', event.target.checked); } catch (e) { console.warn(e); } } handleGenerateDownloadLink(event) { event.preventDefault(); this.setState({ generateDownloadLinkInProgress: true }); this.clickDownload({ generateDownloadLink: true }); } handleClickDownloadLink(event) { const input = this.refs.downloadLinkInput; $(input).focus(); input.setSelectionRange(0, 9999); } copyDownloadLink(event) { const input = this.refs.downloadLinkInput; // select all text in the input $(input).focus(); input.setSelectionRange(0, 9999); try { document.execCommand('copy'); this.setState({ copyClipboardText: 'Copied!' }); } catch (e) { this.setState({ copyClipboardText: 'Press ⌘ + C to copy' }); console.warn('Copy to clipboard is not supported in Safari.') } } copyDownloadLinkMouseOut() { setTimeout(() => { this.setState({ copyClipboardText: 'Copy to clipboard' }); }, 300) } render() { const state = this.state; const settingsCheckboxes = ( <ul className="list-inline list-unstyled clearfix"> <li> <div className="checkbox"> <label> <input type="checkbox" name="beginner" value="beginner" onChange={this.handleChange} checked={state.beginner}/> <span>Beginner</span> </label> </div> </li> <li> <div className="checkbox"> <label> <input type="checkbox" name="disableAutoScroll" value="disableAutoScroll" onChange={this.handleDisableAutoScroll} checked={state.disableAutoScroll}/> <span>Disable auto-scroll</span> </label> </div> </li> <li className="pull-right"> <div className="checkbox"> <a href="https://www.codementor.io/sahatyalkabov?utm_source=github&utm_medium=button&utm_term=sahatyalkabov&utm_campaign=github" target="_blank"><img src="https://cdn.codementor.io/badges/book_session_github.svg" alt="Book session on Codementor"/></a> </div> </li> </ul> ); const platform = ( <Platform {...state} handleChange={this.handleChange}/> ); const staticSiteGenerator = state.platform === 'html5' ? ( <StaticSiteGenerator {...state} handleChange={this.handleChange}/> ) : null; const jsLibrary = state.platform === 'library' ? ( <JsLibrary {...state} handleChange={this.handleChange} handleGenerateLibraryName={this.handleGenerateLibraryName}/> ) : null; const framework = state.platform === 'node' ? ( <Framework {...state} handleChange={this.handleChange}/> ) : null; const cssFramework = state.framework ? ( <CssFramework {...state} handleChange={this.handleChange}/> ) : null; const cssPreprocessor = state.cssFramework ? ( <CssPreprocessor {...state} handleChange={this.handleChange}/> ) : null; const jsFramework = state.cssPreprocessor && state.platform === 'node' ? ( <JsFramework {...state} handleChange={this.handleChange}/> ) : null; const templateEngine = state.jsFramework && state.jsFramework !== 'angularjs' ? ( <TemplateEngine {...state} handleChange={this.handleChange}/> ) : null; const buildTool = (state.jsFramework || (state.jsFramework && state.cssPreprocessor)) && state.platform === 'node' ? ( <BuildTool {...state} handleChange={this.handleChange}/> ) : null; const testing = (state.buildTool || state.cssPreprocessor === 'css' && state.jsFramework === 'none') && state.platform === 'node' ? ( <Testing {...state} handleChange={this.handleChange}/> ) : null; const database = state.testing ? ( <Database {...state} handleChange={this.handleChange}/> ) : null; const authentication = state.database ? ( <Authentication {...state} handleChange={this.handleChange}/> ) : null; const deployment = (state.authentication || state.database === 'none') ? ( <Deployment {...state} handleChange={this.handleChange}/> ) : null; let generateDownloadLink; const loadingSvgColor = state.isDownloadLoading ? '#fff' : '#000'; const loadingSvg = ( <svg version="1.1" id="loader-1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="28px" height="28px" viewBox="0 0 40 40"> <path opacity="0.2" fill={loadingSvgColor} d="M20.201,5.169c-8.254,0-14.946,6.692-14.946,14.946c0,8.255,6.692,14.946,14.946,14.946 s14.946-6.691,14.946-14.946C35.146,11.861,28.455,5.169,20.201,5.169z M20.201,31.749c-6.425,0-11.634-5.208-11.634-11.634 c0-6.425,5.209-11.634,11.634-11.634c6.425,0,11.633,5.209,11.633,11.634C31.834,26.541,26.626,31.749,20.201,31.749z"/> <path fill={loadingSvgColor} d="M26.013,10.047l1.654-2.866c-2.198-1.272-4.743-2.012-7.466-2.012h0v3.312h0 C22.32,8.481,24.301,9.057,26.013,10.047z"> <animateTransform attributeType="xml" attributeName="transform" type="rotate" from="0 20 20" to="360 20 20" dur="0.5s" repeatCount="indefinite"/> </path> </svg> ); if (this.state.generateDownloadLinkSuccess) { generateDownloadLink = ( <div className="row"> <div className="col-sm-8 col-sm-offset-2"> <div className="input-group"> <input type="text" ref="downloadLinkInput" onClick={this.handleClickDownloadLink.bind(this)} className="form-control" defaultValue={state.downloadLinkInputValue} readOnly/> <span className="input-group-btn"> <button onClick={this.copyDownloadLink.bind(this)} onMouseOut={this.copyDownloadLinkMouseOut.bind(this)} className="btn btn-default hint--bottom hint--rounded" type="button" data-hint={this.state.copyClipboardText}> <img className="clipboard" src="https://megaboilerplate.blob.core.windows.net/megaboilerplate/img/svg/clippy.svg" width="13" alt="Copy to clipboard"/> </button> </span> </div> <p className="small text-muted text-right">This link will stay active for 24 hours</p> </div> <br/> </div> ); } else if (this.state.generateDownloadLinkInProgress) { generateDownloadLink = ( <div className="text-center"> <div className="loader"> {loadingSvg} <span>Please wait...</span> </div> </div> ); } else { generateDownloadLink = ( <div> <p onClick={this.handleGenerateDownloadLink.bind(this)} className="text-center">or <a href="#" type="button">Generate Download Link</a></p> </div> ); } const downloadText = state.isDownloadLoading ? loadingSvg : ( <span><i className="fa fa-download"></i> Compile and Download</span> ); const download = state.deployment || state.staticSiteGenerator || state.platform === 'library' || state.platform === 'electron' ? ( <div> <button ref="downloadBtn" className="btn btn-block btn-mega btn-success" onClick={this.clickDownload}>{downloadText}</button> {generateDownloadLink} </div> ) : null; const nextSteps = state.showNextSteps ? ( <NextSteps {...state}/> ) : null; return ( <div ref="wrapper"> <Header /> <main className="container"> {settingsCheckboxes} <div ref="platform">{platform}</div> <div ref="framework">{framework}</div> <div ref="staticSiteGenerator">{staticSiteGenerator}</div> <div ref="jsLibrary">{jsLibrary}</div> <div ref="cssFramework">{cssFramework}</div> <div ref="cssPreprocessor">{cssPreprocessor}</div> <div ref="jsFramework">{jsFramework}</div> <div ref="templateEngine">{templateEngine}</div> <div ref="buildTool">{buildTool}</div> <div ref="testing">{testing}</div> <div ref="database">{database}</div> <div ref="authentication">{authentication}</div> <div ref="deployment">{deployment}</div> <div ref="download">{download}</div> <div ref="nextSteps">{nextSteps}</div> </main> <Footer /> <div className="modal" id="demosModal" tabIndex="-1" role="dialog"> <div className="modal-dialog" role="document"> <div className="modal-content"> <div className="modal-header"> <button type="button" className="close" data-dismiss="modal"><span aria-hidden="true">&times;</span> </button> <h4 className="modal-title" id="myModalLabel"><i className="fa fa-globe"></i> Live Demos</h4> </div> <div className="modal-body"> <a href="http://megaboilerplate-demo1.azurewebsites.net/" className="demo-container demo1" target="_blank"> <p><span><strong>Demo 1</strong> - Traditional Express web app</span> <img src="https://megaboilerplate.blob.core.windows.net/megaboilerplate/img/svg/recommended.svg" alt="Recommended"/> </p> <span className="text-normal">Node - Jade - Bootstrap - Sass - Mocha - MongoBD - Facebook - Google - Twitter - VK</span> </a> <a href="http://megaboilerplate-demo2.azurewebsites.net/" className="demo-container demo2" target="_blank"> <p><span><strong>Demo 2</strong> - MEAN stack</span></p> <span className="text-normal">Node - Handlebars - Foundation - AngularJS - Gulp - Jasmine - MongoDB - Facebook - Google</span> </a> <a href="http://megaboilerplate-demo3.azurewebsites.net/ " className="demo-container demo3" target="_blank"> <p><span><strong>Demo 3</strong> - Full-stack React app (unstyled)</span></p> <span className="text-normal">Node - Nunjucks - CSSNext - PostCSS - React - Webpack - Mocha - SQLite - Twitter</span> </a> <a href="https://github.com/sahat/megaboilerplate/tree/master/examples/jekyll#mega-boilerplate-jekyll-blog-example" className="demo-container demo4" target="_blank"> <p><span><strong>Demo 4</strong> - Jekyll blo</span>g</p> <span className="text-normal">Ruby - Jekyll</span> </a> <a href="https://github.com/sahat/megaboilerplate/tree/master/examples/middleman#mega-boilerplate-middleman-site-example" className="demo-container demo5" target="_blank"> <p><span><strong>Demo 5</strong> - Middleman static site</span></p> <span className="text-normal">Ruby - Middleman</span> </a> </div> </div> </div> </div> </div> ); } } export default Home;
src/svg-icons/action/redeem.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionRedeem = (props) => ( <SvgIcon {...props}> <path d="M20 6h-2.18c.11-.31.18-.65.18-1 0-1.66-1.34-3-3-3-1.05 0-1.96.54-2.5 1.35l-.5.67-.5-.68C10.96 2.54 10.05 2 9 2 7.34 2 6 3.34 6 5c0 .35.07.69.18 1H4c-1.11 0-1.99.89-1.99 2L2 19c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2zm-5-2c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zM9 4c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm11 15H4v-2h16v2zm0-5H4V8h5.08L7 10.83 8.62 12 11 8.76l1-1.36 1 1.36L15.38 12 17 10.83 14.92 8H20v6z"/> </SvgIcon> ); ActionRedeem = pure(ActionRedeem); ActionRedeem.displayName = 'ActionRedeem'; ActionRedeem.muiName = 'SvgIcon'; export default ActionRedeem;
ajax/libs/forerunnerdb/1.3.522/fdb-core+persist.min.js
sufuf3/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/Persist");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/Persist":28,"./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":6,"../lib/Shim.IE8":34}],3:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=new e,g=function(a,b,c){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c,d,e){this._store=[],this._keys=[],void 0!==c&&this.primaryKey(c),void 0!==b&&this.index(b),void 0!==d&&this.compareFunc(d),void 0!==e&&this.hashFunc(e),void 0!==a&&this.data(a)},d.addModule("BinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),d.mixin(g.prototype,"Mixin.Common"),d.synthesize(g.prototype,"compareFunc"),d.synthesize(g.prototype,"hashFunc"),d.synthesize(g.prototype,"indexDir"),d.synthesize(g.prototype,"primaryKey"),d.synthesize(g.prototype,"keys"),d.synthesize(g.prototype,"index",function(a){return void 0!==a&&(this.debug()&&console.log("Setting index",a,f.parse(a,!0)),this.keys(f.parse(a,!0))),this.$super.call(this,a)}),g.prototype.clear=function(){delete this._data,delete this._left,delete this._right,this._store=[]},g.prototype.data=function(a){return void 0!==a?(this._data=a,this._hashFunc&&(this._hash=this._hashFunc(a)),this):this._data},g.prototype.push=function(a){return void 0!==a?(this._store.push(a),this):!1},g.prototype.pull=function(a){if(void 0!==a){var b=this._store.indexOf(a);if(b>-1)return this._store.splice(b,1),this}return!1},g.prototype._compareFunc=function(a,b){var c,d,e=0;for(c=0;c<this._keys.length;c++)if(d=this._keys[c],1===d.value?e=this.sortAsc(f.get(a,d.path),f.get(b,d.path)):-1===d.value&&(e=this.sortDesc(f.get(a,d.path),f.get(b,d.path))),this.debug()&&console.log("Compared %s with %s order %d in path %s and result was %d",f.get(a,d.path),f.get(b,d.path),d.value,d.path,e),0!==e)return this.debug()&&console.log("Retuning result %d",e),e;return this.debug()&&console.log("Retuning result %d",e),e},g.prototype._hashFunc=function(a){return a[this._keys[0].path]},g.prototype.removeChildNode=function(a){this._left===a?delete this._left:this._right===a&&delete this._right},g.prototype.nodeBranch=function(a){return this._left===a?"left":this._right===a?"right":void 0},g.prototype.insert=function(a){var b,c,d,e;if(a instanceof Array){for(c=[],d=[],e=0;e<a.length;e++)this.insert(a[e])?c.push(a[e]):d.push(a[e]);return{inserted:c,failed:d}}return this.debug()&&console.log("Inserting",a),this._data?(b=this._compareFunc(this._data,a),0===b?(this.debug()&&console.log("Data is equal (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):-1===b?(this.debug()&&console.log("Data is greater (currrent, new)",this._data,a),this._right?this._right.insert(a):(this._right=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._right._parent=this),!0):1===b?(this.debug()&&console.log("Data is less (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):!1):(this.debug()&&console.log("Node has no data, setting data",a),this.data(a),!0)},g.prototype.remove=function(a){var b,c,d,e=this.primaryKey();if(a instanceof Array){for(c=[],d=0;d<a.length;d++)this.remove(a[d])&&c.push(a[d]);return c}return this.debug()&&console.log("Removing",a),this._data[e]===a[e]?this._remove(this):(b=this._compareFunc(this._data,a),-1===b&&this._right?this._right.remove(a):1===b&&this._left?this._left.remove(a):!1)},g.prototype._remove=function(a){var b,c;return this._left?(b=this._left,c=this._right,this._left=b._left,this._right=b._right,this._data=b._data,this._store=b._store,c&&(b.rightMost()._right=c)):this._right?(c=this._right,this._left=c._left,this._right=c._right,this._data=c._data,this._store=c._store):this.clear(),!0},g.prototype.leftMost=function(){return this._left?this._left.leftMost():this},g.prototype.rightMost=function(){return this._right?this._right.rightMost():this},g.prototype.lookup=function(a,b,c){var d=this._compareFunc(this._data,a);return c=c||[],0===d&&(this._left&&this._left.lookup(a,b,c),c.push(this._data),this._right&&this._right.lookup(a,b,c)),-1===d&&this._right&&this._right.lookup(a,b,c),1===d&&this._left&&this._left.lookup(a,b,c),c},g.prototype.inOrder=function(a,b){switch(b=b||[],this._left&&this._left.inOrder(a,b),a){case"hash":b.push(this._hash);break;case"data":b.push(this._data);break;default:b.push({key:this._data,arr:this._store})}return this._right&&this._right.inOrder(a,b),b},g.prototype.startsWith=function(a,b,c,d){var e,g,h=f.get(this._data,a),i=h.substr(0,b.length);return c=c||new RegExp("^"+b),d=d||[],void 0===d._visited&&(d._visited=0),d._visited++,g=this.sortAsc(h,b),e=i===b,0===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),-1===g&&(e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),1===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data)),d},g.prototype.findRange=function(a,b,c,d,f,g){f=f||[],g=g||new e(b),this._left&&this._left.findRange(a,b,c,d,f,g);var h=g.value(this._data),i=this.sortAsc(h,c),j=this.sortAsc(h,d);if(!(0!==i&&1!==i||0!==j&&-1!==j))switch(a){case"hash":f.push(this._hash);break;case"data":f.push(this._data);break;default:f.push({key:this._data,arr:this._store})}return this._right&&this._right.findRange(a,b,c,d,f,g),f},g.prototype.match=function(a,b,c){var d,e,g,h=[],i=0;for(d=f.parseArr(this._index,{verbose:!0}),e=f.parseArr(a,c&&c.pathOptions?c.pathOptions:{ignore:/\$/,verbose:!0}),g=0;g<d.length;g++)e[g]===d[g]&&(i++,h.push(e[g]));return{matchedKeys:h,totalKeyCount:e.length,score:i}},d.finishModule("BinaryTree"),b.exports=g},{"./Path":27,"./Shared":33}],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){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),this.debug()&&console.log(this.logIdentifier()+" Updating some data");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&&(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=this.find(a,b);return(new p).subsetOf(this).primaryKey(this._primaryKey).setData(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.apply(this,arguments)},p.prototype._find=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";a=a||{},b=this.options(b);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=this._metrics.create("find"),J=this.primaryKey(),K=this,L=!0,M={},N=[],O=[],P=[],Q={},R={},S=function(c){return K._match(c,a,b,"and",Q)};if(I.start(),a){if(I.time("analyseQuery"),c=this._analyseQuery(K.decouple(a),b,I),I.time("analyseQuery"),I.data("analysis",c),c.hasJoin&&c.queriesJoin){for(I.time("joinReferences"),g=0;g<c.joinsOn.length;g++)k=c.joinsOn[g],j=new h(c.joinQueries[k]),i=j.value(a)[0],M[c.joinsOn[g]]=this._db.collection(c.joinsOn[g]).subset(i),delete a[c.joinQueries[k]];I.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(I.data("index.potential",c.indexMatch),I.data("index.used",c.indexMatch[0].index),I.time("indexLookup"),e=c.indexMatch[0].lookup||[],I.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(L=!1)):I.flag("usedIndex",!1),L&&(e&&e.length?(d=e.length,I.time("tableScan: "+d),e=e.filter(S)):(d=this._data.length,I.time("tableScan: "+d),e=this._data.filter(S)),I.time("tableScan: "+d)),b.$orderBy&&(I.time("sort"),e=this.sort(b.$orderBy,e),I.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(R.page=b.$page,R.pages=Math.ceil(e.length/b.$limit),R.records=e.length,b.$page&&b.$limit>0&&(I.data("cursor",R),e.splice(0,b.$page*b.$limit))),b.$skip&&(R.skip=b.$skip,e.splice(0,b.$skip),I.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(R.limit=b.$limit,e.length=b.$limit,I.data("limit",b.$limit)),b.$decouple&&(I.time("decouple"),e=this.decouple(e),I.time("decouple"),I.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(w=k,l=M[k]?M[k]:this._db.collection(k),m=b.$join[f][k],x=0;x<e.length;x++){o={},q=!1,r=!1,v="";for(n in m)if(m.hasOwnProperty(n))if("$"===n.substr(0,1))switch(n){case"$where":m[n].query&&(o=K._resolveDynamicQuery(m[n].query,e[x])),m[n].options&&(p=m[n].options);break;case"$as":w=m[n];break;case"$multi":q=m[n];break;case"$require":r=m[n];break;case"$prefix":v=m[n]}else o[n]=K._resolveDynamicQuery(m[n],e[x]);if(s=l.find(o,p),!r||r&&s[0])if("$root"===w){if(q!==!1)throw this.logIdentifier()+' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!';t=s[0],u=e[x];for(C in t)t.hasOwnProperty(C)&&void 0===u[v+C]&&(u[v+C]=t[C])}else e[x][w]=q===!1?s[0]:s;else N.push(e[x])}I.data("flag.join",!0)}if(N.length){for(I.time("removalQueue"),z=0;z<N.length;z++)y=e.indexOf(N[z]),y>-1&&e.splice(y,1);I.time("removalQueue")}if(b.$transform){for(I.time("transform"),z=0;z<e.length;z++)e.splice(z,1,b.$transform(e[z]));I.time("transform"),I.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(I.time("transformOut"),e=this.transformOut(e),I.time("transformOut")),I.data("results",e.length)}else e=[];if(!b.$aggregate){I.time("scanFields");for(z in b)b.hasOwnProperty(z)&&0!==z.indexOf("$")&&(1===b[z]?O.push(z):0===b[z]&&P.push(z));if(I.time("scanFields"),O.length||P.length){for(I.data("flag.limitFields",!0),I.data("limitFields.on",O),I.data("limitFields.off",P),I.time("limitFields"),z=0;z<e.length;z++){G=e[z];for(A in G)G.hasOwnProperty(A)&&(O.length&&A!==J&&-1===O.indexOf(A)&&delete G[A],P.length&&P.indexOf(A)>-1&&delete G[A])}I.time("limitFields")}if(b.$elemMatch){I.data("flag.elemMatch",!0),I.time("projection-elemMatch");for(z in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(z))for(D=new h(z),A=0;A<e.length;A++)if(E=D.value(e[A])[0],E&&E.length)for(B=0;B<E.length;B++)if(K._match(E[B],b.$elemMatch[z],b,"",{})){D.set(e[A],z,[E[B]]);break}I.time("projection-elemMatch")}if(b.$elemsMatch){I.data("flag.elemsMatch",!0),I.time("projection-elemsMatch");for(z in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(z))for(D=new h(z),A=0;A<e.length;A++)if(E=D.value(e[A])[0],E&&E.length){for(F=[],B=0;B<E.length;B++)K._match(E[B],b.$elemsMatch[z],b,"",{})&&F.push(E[B]);D.set(e[A],z,F)}I.time("projection-elemsMatch")}}return b.$aggregate&&(I.data("flag.aggregate",!0),I.time("aggregate"),H=new h(b.$aggregate),e=H.value(e),I.time("aggregate")),I.stop(),e.__fdbOp=I,e.$cursor=R,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=[];for(b=0;b<a.length;b++)c[b]=this._transformIn(a[b]);return c}return this._transformIn(a)}return a},p.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformOut(a[b]);return c}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.bucket=function(a,b){var c,d,e,f=[],g={};for(c=0;c<b.length;c++)e=String(b[c][a]),d!==e&&(f.push(e),d=e),g[e]=g[e]||[],g[e].push(b[c]);return{buckets:g,order:f}},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){var e,f,g,i=new h(b),j=this.find(a),k=j.length,l=this._db.collection("__FDB_temp_"+this.objectId()),m={parents:k,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(d=d||{},e=0;k>e;e++)if(f=i.value(j[e])[0]){if(l.setData(f),g=l.find(c,d),d.returnFirst&&g.length)return g[0];d.$split?m.subDocs.push(g):m.subDocs=m.subDocs.concat(g),m.subDocTotal+=g.length,m.pathFound=!0}return l.drop(),d.$stats?m:m.subDocs},p.prototype.findSubOne=function(a,b,c,d){return this.findSub(a,b,c,d)[0]},p.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return b?b.name():!1},p.prototype.ensureIndex=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,d={start:(new Date).getTime()};if(b)switch(b.type){case"hashed":c=new i(a,b,this);break;case"btree":c=new j(a,b,this);break;case"2d":c=new k(a,b,this);break;default:c=new i(a,b,this)}else c=new i(a,b,this);return this._indexByName[c.name()]?{err:"Index with that name already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,d.end=(new Date).getTime(),d.total=d.end-d.start,this._lastOp={type:"ensureIndex",stats:{time:d}},{index:c,id:c.id(),name:c.name(),state:c.state()})},p.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},p.prototype.lastOp=function(){return this._metrics.list()},p.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw this.logIdentifier()+" Diffing requires that both collections have the same primary key!";for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},p.prototype.collateAdd=new m({"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":b?(e={$push:{}},e.$push[b]=c.decouple(d.data),c.update({},e)):c.insert(d.data);break;case"update":b?(e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f)):c.update(d.data.query,d.data.update);break;case"remove":b?(e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)):c.remove(d.data)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new n(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),p.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},e.prototype.collection=new m({"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof p?"droppped"!==a.state()?a:this.$main.call(this,{name:a.name()}):this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=this,c=a.name;if(c){if(this._collection[c])return this._collection[c];if(a&&a.autoCreate===!1){if(a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection "+c+" because it does not exist and auto-create has been disabled!";return}if(this.debug()&&console.log(this.logIdentifier()+" Creating collection "+c),this._collection[c]=this._collection[c]||new p(c,a).db(this),this._collection[c].mongoEmulation(this.mongoEmulation()),void 0!==a.primaryKey&&this._collection[c].primaryKey(a.primaryKey),void 0!==a.capped){if(void 0===a.size)throw this.logIdentifier()+" Cannot create a capped collection without specifying a size!";this._collection[c].capped(a.capped),this._collection[c].cappedSize(a.size)}return b._collection[c].on("change",function(){b.emit("change",b._collection[c],"collection",c)}),b.emit("create",b._collection[c],"collection",c),this._collection[c]}if(!a||a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection with undefined name!"}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c,d=[],e=this._collection;a&&(a instanceof RegExp||(a=new RegExp(a)));for(c in e)e.hasOwnProperty(c)&&(b=e[c],a?a.exec(c)&&d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}):d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}));return d.sort(function(a,b){return a.name.localeCompare(b.name)}),d},d.finishModule("Collection"),b.exports=p},{"./Crc":7,"./Index2d":10,"./IndexBinaryTree":11,"./IndexHashMap":12,"./KeyValueStore":13,"./Metrics":14,"./Overload":26,"./Path":27,"./ReactorIO":31,"./Shared":33}],5:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;b._name=a,b._data=new g("__FDB__cg_data_"+b._name),b._collections=[],b._view=[]},d.addModule("CollectionGroup",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Tags"),g=a("./Collection"),e=d.modules.Db,f=d.modules.Db.prototype.init,h.prototype.on=function(){this._data.on.apply(this._data,arguments)},h.prototype.off=function(){this._data.off.apply(this._data,arguments)},h.prototype.emit=function(){this._data.emit.apply(this._data,arguments)},h.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),h.prototype.addCollection=function(a){if(a&&-1===this._collections.indexOf(a)){if(this._collections.length){if(this._primaryKey!==a.primaryKey())throw this.logIdentifier()+" All collections in a collection group must have the same primary key!"}else this.primaryKey(a.primaryKey());this._collections.push(a),a._groups=a._groups||[],a._groups.push(this),a.chain(this),a.on("drop",function(){if(a._groups&&a._groups.length){var b,c=[];for(b=0;b<a._groups.length;b++)c.push(a._groups[b]);for(b=0;b<c.length;b++)a._groups[b].removeCollection(a)}delete a._groups}),this._data.insert(a.find())}return this},h.prototype.removeCollection=function(a){if(a){var b,c=this._collections.indexOf(a);-1!==c&&(a.unChain(this),this._collections.splice(c,1),a._groups=a._groups||[],b=a._groups.indexOf(this),-1!==b&&a._groups.splice(b,1),a.off("drop")),0===this._collections.length&&delete this._primaryKey}return this},h.prototype._chainHandler=function(a){switch(a.type){case"setData":a.data=this.decouple(a.data),this._data.remove(a.options.oldData),this._data.insert(a.data);break;case"insert":a.data=this.decouple(a.data),this._data.insert(a.data);break;case"update":this._data.update(a.data.query,a.data.update,a.options);break;case"remove":this._data.remove(a.data.query,a.options)}},h.prototype.insert=function(){this._collectionsRun("insert",arguments)},h.prototype.update=function(){this._collectionsRun("update",arguments)},h.prototype.updateById=function(){this._collectionsRun("updateById",arguments)},h.prototype.remove=function(){this._collectionsRun("remove",arguments)},h.prototype._collectionsRun=function(a,b){for(var c=0;c<this._collections.length;c++)this._collections[c][a].apply(this._collections[c],b)},h.prototype.find=function(a,b){return this._data.find(a,b)},h.prototype.removeById=function(a){for(var b=0;b<this._collections.length;b++)this._collections[b].removeById(a)},h.prototype.subset=function(a,b){var c=this.find(a,b);return(new g).subsetOf(this).primaryKey(this._primaryKey).setData(c)},h.prototype.drop=function(a){if(!this.isDropped()){var b,c,d;if(this._debug&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._collections&&this._collections.length)for(c=[].concat(this._collections),b=0;b<c.length;b++)this.removeCollection(c[b]);if(this._view&&this._view.length)for(d=[].concat(this._view),b=0;b<d.length;b++)this._removeView(d[b]);this.emit("drop",this),delete this._listeners,a&&a(!1,!0)}return!0},e.prototype.init=function(){this._collectionGroup={},f.apply(this,arguments)},e.prototype.collectionGroup=function(a){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":4,"./Shared":33}],6:[function(a,b,c){"use strict";var d,e,f,g,h=[];d=a("./Shared"),g=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._db={},this._debug={},this._name=a||"ForerunnerDB",h.push(this)},i.prototype.instantiatedCount=function(){return h.length},i.prototype.instances=function(a){return void 0!==a?h[a]:h},i.prototype.namedInstances=function(a){var b,c;{if(void 0===a){for(c=[],b=0;b<h.length;b++)c.push(h[b].name);return c}for(b=0;b<h.length;b++)if(h[b].name===a)return h[b]}},i.prototype.moduleLoaded=new g({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"array, function":function(a,b){var c,e;for(e=0;e<a.length;e++)if(c=a[e],void 0!==c){c=c.replace(/ /g,"");var f,g=c.split(",");for(f=0;f<g.length;f++)if(!d.modules[g[f]])return!1}b&&b()},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.instances=i.prototype.instances,i.instantiatedCount=i.prototype.instantiatedCount,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype._isServer=!1,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.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":14,"./Overload":26,"./Shared":33}],7:[function(a,b,c){"use strict";var d=function(){var a,b,c,d=[];for(b=0;256>b;b++){for(a=b,c=0;8>c;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}();b.exports=function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^d[255&(c^a.charCodeAt(b))];return(-1^c)>>>0}},{}],8:[function(a,b,c){"use strict";var d,e,f,g,h,i;d=a("./Shared"),i=a("./Overload");var j=function(a,b){this.init.apply(this,arguments)};j.prototype.init=function(a,b){this.core(b),this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},d.addModule("Db",j),j.prototype.moduleLoaded=new i({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),j.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},j.moduleLoaded=j.prototype.moduleLoaded,j.version=j.prototype.version,j.shared=d,j.prototype.shared=d,d.addModule("Db",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Constants"),d.mixin(j.prototype,"Mixin.Tags"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./Crc.js"),j.prototype._isServer=!1,d.synthesize(j.prototype,"core"),d.synthesize(j.prototype,"primaryKey"),d.synthesize(j.prototype,"state"),d.synthesize(j.prototype,"name"),d.synthesize(j.prototype,"mongoEmulation"),j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.crc=h,j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.arrayToCollection=function(a){return(new f).setData(a)},j.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},j.prototype.off=function(a,b){if(a in this._listeners){var c=this._listeners[a],d=c.indexOf(b);d>-1&&c.splice(d,1)}return this},j.prototype.emit=function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d=this._listeners[a],e=d.length;for(c=0;e>c;c++)d[c].apply(this,Array.prototype.slice.call(arguments,1))}return this},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},j.prototype.drop=new i({"":function(){if(!this.isDropped()){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;c>a;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"function":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if(!this.isDropped()){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;e>c;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a instanceof j?a:(a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a,this),this._db[a].mongoEmulation(this.mongoEmulation()),this._db[a])},e.prototype.databases=function(a){var b,c,d,e=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(d in this._db)this._db.hasOwnProperty(d)&&(c=!0,a&&(a.exec(d)||(c=!1)),c&&(b={name:d,children:[]},this.shared.moduleExists("Collection")&&b.children.push({module:"collection",moduleName:"Collections",count:this._db[d].collections().length}),this.shared.moduleExists("CollectionGroup")&&b.children.push({module:"collectionGroup",moduleName:"Collection Groups",count:this._db[d].collectionGroups().length}),this.shared.moduleExists("Document")&&b.children.push({module:"document",moduleName:"Documents",count:this._db[d].documents().length}),this.shared.moduleExists("Grid")&&b.children.push({module:"grid",moduleName:"Grids",count:this._db[d].grids().length}),this.shared.moduleExists("Overview")&&b.children.push({module:"overview",moduleName:"Overviews",count:this._db[d].overviews().length}),this.shared.moduleExists("View")&&b.children.push({module:"view",moduleName:"Views",count:this._db[d].views().length}),e.push(b)));return e.sort(function(a,b){return a.name.localeCompare(b.name)}),e},d.finishModule("Db"),b.exports=j},{"./Collection.js":4,"./Crc.js":7,"./Metrics.js":14,"./Overload":26,"./Shared":33}],9:[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},{}],10:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=a("./Geohash"),h=new e,i=new g,j=[5e3,1250,156,39.1,4.89,1.22,.153,.0382,.00477,.00119,149e-6,372e-7],k=function(){this.init.apply(this,arguments)};k.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("Index2d",k),d.mixin(k.prototype,"Mixin.Common"),d.mixin(k.prototype,"Mixin.ChainReactor"),d.mixin(k.prototype,"Mixin.Sorting"),k.prototype.id=function(){return this._id},k.prototype.state=function(){return this._state},k.prototype.size=function(){return this._size},d.synthesize(k.prototype,"data"),d.synthesize(k.prototype,"name"),d.synthesize(k.prototype,"collection"),d.synthesize(k.prototype,"type"),d.synthesize(k.prototype,"unique"),k.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=h.parse(this._keys).length,this):this._keys},k.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},k.prototype.insert=function(a,b){var c,d=this._unique;a=this.decouple(a),d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a);var e,f,g,j,k,l=this._btree.keys();for(k=0;k<l.length;k++)e=h.get(a,l[k].path),e instanceof Array&&(g=e[0],j=e[1],f=i.encode(g,j),h.set(a,l[k].path,f));return this._btree.insert(a)?(this._size++,!0):!1},k.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},k.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},k.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},k.prototype.lookup=function(a,b){var c,d,e,f,g=this._btree.keys();for(f=0;f<g.length;f++)if(c=g[f].path,d=h.get(a,c),"object"==typeof d)return d.$near&&(e=[],e=e.concat(this.near(c,d.$near,b))),d.$geoWithin&&(e=[],e=e.concat(this.geoWithin(c,d.$geoWithin,b))),e;return this._btree.lookup(a,b)},k.prototype.near=function(a,b,c){var d,e,f,g,k,l,m,n,o,p,q,r=this,s=[],t=this._collection.primaryKey();if("km"===b.$distanceUnits){for(m=b.$maxDistance,q=0;q<j.length;q++)if(m>j[q]){l=q;break}0===l&&(l=1)}else if("miles"===b.$distanceUnits){for(m=1.60934*b.$maxDistance,q=0;q<j.length;q++)if(m>j[q]){l=q;break}0===l&&(l=1)}for(d=i.encode(b.$point[0],b.$point[1],l),e=i.calculateNeighbours(d,{type:"array"}),k=[],f=0,q=0;9>q;q++)g=this._btree.startsWith(a,e[q]),f+=g._visited,k=k.concat(g);if(k=this._collection._primaryIndex.lookup(k),k.length){for(n={},q=0;q<k.length;q++)p=h.get(k[q],a),o=n[k[q][t]]=this.distanceBetweenPoints(b.$point[0],b.$point[1],p[0],p[1]),m>=o&&s.push(k[q]);s.sort(function(a,b){return r.sortAsc(n[a[t]],n[b[t]])})}return s},k.prototype.geoWithin=function(a,b,c){return[]},k.prototype.distanceBetweenPoints=function(a,b,c,d){var e=6371,f=this.toRadians(a),g=this.toRadians(c),h=this.toRadians(c-a),i=this.toRadians(d-b),j=Math.sin(h/2)*Math.sin(h/2)+Math.cos(f)*Math.cos(g)*Math.sin(i/2)*Math.sin(i/2),k=2*Math.atan2(Math.sqrt(j),Math.sqrt(1-j));return e*k},k.prototype.toRadians=function(a){return.01747722222222*a},k.prototype.match=function(a,b){return this._btree.match(a,b)},k.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},k.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},k.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("Index2d"),b.exports=k},{"./BinaryTree":3,"./Geohash":9,"./Path":27,"./Shared":33}],11:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("IndexBinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),g.prototype.id=function(){return this._id},g.prototype.state=function(){return this._state},g.prototype.size=function(){return this._size},d.synthesize(g.prototype,"data"),d.synthesize(g.prototype,"name"),d.synthesize(g.prototype,"collection"),d.synthesize(g.prototype,"type"),d.synthesize(g.prototype,"unique"),g.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},g.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},g.prototype.insert=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),this._btree.insert(a)?(this._size++,!0):!1},g.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},g.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},g.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},g.prototype.lookup=function(a,b){return this._btree.lookup(a,b)},g.prototype.match=function(a,b){return this._btree.match(a,b)},g.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},g.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},g.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexBinaryTree"),b.exports=g},{"./BinaryTree":3,"./Path":27,"./Shared":33}],12:[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":27,"./Shared":33}],13:[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":33}],14:[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":25,"./Shared":33}],15:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],16:[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(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},{}],17:[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){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":26,"./Serialiser":32}],18:[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},{}],19:[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":26}],20:[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(!this.db())throw"Cannot operate a "+a+" sub-query on an anonymous collection (one with no db set)!";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!";v=c.$path,t=c.$subQuery||{},u=c.$subOptions||{},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},{}],21:[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},{}],22:[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},{}],23:[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":26}],24:[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},{}],25:[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":27,"./Shared":33}],26:[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 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},{}],27:[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":33}],28:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m=a("./Shared"),n=a("async"),o=a("localforage");a("./PersistCompress"),a("./PersistCrypto");k=function(){this.init.apply(this,arguments)},k.prototype.localforage=o,k.prototype.init=function(a){var b=this;this._encodeSteps=[function(){return b._encode.apply(b,arguments)}],this._decodeSteps=[function(){return b._decode.apply(b,arguments)}],a.isClient()&&void 0!==window.Storage&&(this.mode("localforage"),o.config({driver:[o.INDEXEDDB,o.WEBSQL,o.LOCALSTORAGE],name:String(a.core().name()),storeName:"FDB"}))},m.addModule("Persist",k),m.mixin(k.prototype,"Mixin.ChainReactor"),m.mixin(k.prototype,"Mixin.Common"),d=m.modules.Db,e=a("./Collection"),f=e.prototype.drop,g=a("./CollectionGroup"),h=e.prototype.init,i=d.prototype.init,j=d.prototype.drop,l=m.overload,m.synthesize(k.prototype,"auto",function(a){var b=this;return void 0!==a&&(a?(this._db.on("create",function(){b._autoLoad.apply(b,arguments)}),this._db.on("change",function(){b._autoSave.apply(b,arguments)}),this._db.debug()&&console.log(this._db.logIdentifier()+" Automatic load/save enabled")):(this._db.off("create",this._autoLoad),this._db.off("change",this._autoSave),this._db.debug()&&console.log(this._db.logIdentifier()+" Automatic load/save disbled"))),this.$super.call(this,a)}),k.prototype._autoLoad=function(a,b,c){var d=this;"function"==typeof a.load?(d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-loading data for "+b+":",c),a.load(function(a,b){a&&d._db.debug()&&console.log(d._db.logIdentifier()+" Automatic load failed:",a),d.emit("load",a,b)})):d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-load for "+b+":",c,"no load method, skipping")},k.prototype._autoSave=function(a,b,c){var d=this;"function"==typeof a.save&&(d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-saving data for "+b+":",c),a.save(function(a,b){a&&d._db.debug()&&console.log(d._db.logIdentifier()+" Automatic save failed:",a),d.emit("save",a,b)}))},k.prototype.mode=function(a){return void 0!==a?(this._mode=a,this):this._mode},k.prototype.driver=function(a){if(void 0!==a){switch(a.toUpperCase()){case"LOCALSTORAGE":o.setDriver(o.LOCALSTORAGE);break;case"WEBSQL":o.setDriver(o.WEBSQL);break;case"INDEXEDDB":o.setDriver(o.INDEXEDDB);break;default:throw"ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!"}return this}return o.driver()},k.prototype.decode=function(a,b){n.waterfall([function(b){b&&b(!1,a,{})}].concat(this._decodeSteps),b)},k.prototype.encode=function(a,b){n.waterfall([function(b){b&&b(!1,a,{})}].concat(this._encodeSteps),b)},m.synthesize(k.prototype,"encodeSteps"),m.synthesize(k.prototype,"decodeSteps"),k.prototype.addStep=new l({object:function(a){this.$main.call(this,function(){a.encode.apply(a,arguments)},function(){a.decode.apply(a,arguments)},0)},"function, function":function(a,b){this.$main.call(this,a,b,0)},"function, function, number":function(a,b,c){this.$main.call(this,a,b,c)},$main:function(a,b,c){0===c||void 0===c?(this._encodeSteps.push(a),this._decodeSteps.unshift(b)):(this._encodeSteps.splice(c,0,a),this._decodeSteps.splice(this._decodeSteps.length-c,0,b))}}),k.prototype.unwrap=function(a){var b,c=a.split("::fdb::");switch(c[0]){case"json":b=this.jParse(c[1]);break;case"raw":b=c[1]}},k.prototype._decode=function(a,b,c){var d,e;if(a){switch(d=a.split("::fdb::"),d[0]){case"json":e=this.jParse(d[1]);break;case"raw":e=d[1]}e?(b.foundData=!0,b.rowCount=e.length):b.foundData=!1,c&&c(!1,e,b)}else b.foundData=!1,b.rowCount=0,c&&c(!1,a,b)},k.prototype._encode=function(a,b,c){var d=a;a="object"==typeof a?"json::fdb::"+this.jStringify(a):"raw::fdb::"+a,d?(b.foundData=!0,b.rowCount=d.length):b.foundData=!1,c&&c(!1,a,b)},k.prototype.save=function(a,b,c){switch(this.mode()){case"localforage":this.encode(b,function(b,d,e){o.setItem(a,d).then(function(a){c&&c(!1,a,e)},function(a){c&&c(a)})});break;default:c&&c("No data handler.")}},k.prototype.load=function(a,b){var c=this;switch(this.mode()){case"localforage":o.getItem(a).then(function(a){c.decode(a,b)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},k.prototype.drop=function(a,b){switch(this.mode()){case"localforage":o.removeItem(a).then(function(){b&&b(!1)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},e.prototype.drop=new l({"":function(){this.isDropped()||this.drop(!0)},"function":function(a){this.isDropped()||this.drop(!0,a)},"boolean":function(a){if(!this.isDropped()){if(a){if(!this._name)throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when no name assigned to collection!";this._db&&(this._db.persist.drop(this._db._name+"-"+this._name),this._db.persist.drop(this._db._name+"-"+this._name+"-metaData"))}f.call(this)}},"boolean, function":function(a,b){var c=this;if(!this.isDropped()){if(!a)return f.call(this,b);if(this._name){if(this._db)return this._db.persist.drop(this._db._name+"-"+this._name,function(){c._db.persist.drop(c._db._name+"-"+c._name+"-metaData",b)}),f.call(this);b&&b("Cannot drop a collection's persistent storage when the collection is not attached to a database!")}else b&&b("Cannot drop a collection's persistent storage when no name assigned to collection!")}}}),e.prototype.save=function(a){var b,c=this;c._name?c._db?(b=function(){c._db.persist.save(c._db._name+"-"+c._name,c._data,function(b,d,e){b?a&&a(b):c._db.persist.save(c._db._name+"-"+c._name+"-metaData",c.metaData(),function(b,c,d){a&&a(b,c,e,d)})})},c.isProcessingQueue()?c.on("queuesComplete",function(){b()}):b()):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.load=function(a){var b=this;b._name?b._db?b._db.persist.load(b._db._name+"-"+b._name,function(c,d,e){c?a&&a(c):(d&&(b.remove({}),b.insert(d)),b._db.persist.load(b._db._name+"-"+b._name+"-metaData",function(c,d,f){c||d&&b.metaData(d),a&&a(c,e,f)}))}):a&&a("Cannot load a collection that is not attached to a database!"):a&&a("Cannot load a collection with no assigned name!")},e.prototype.saveCustom=function(a){var b,c=this,d={};c._name?c._db?(b=function(){c.encode(c._data,function(b,e,f){b?a(b):(d.data={name:c._db._name+"-"+c._name,store:e,tableStats:f},c.encode(c._data,function(b,e,f){b?a(b):(d.metaData={name:c._db._name+"-"+c._name+"-metaData",store:e,tableStats:f},a(!1,d))}))})},c.isProcessingQueue()?c.on("queuesComplete",function(){b()}):b()):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.loadCustom=function(a,b){var c=this;c._name?c._db?a.data&&a.data.store?a.metaData&&a.metaData.store?c.decode(a.data.store,function(d,e,f){d?b(d):e&&(c.remove({}),c.insert(e),c.decode(a.metaData.store,function(a,d,e){a?b(a):d&&(c.metaData(d),b&&b(a,f,e))}))}):b('No "metaData" key found in passed object!'):b('No "data" key found in passed object!'):b&&b("Cannot load a collection that is not attached to a database!"):b&&b("Cannot load a collection with no assigned name!")},d.prototype.init=function(){i.apply(this,arguments),this.persist=new k(this)},d.prototype.load=new l({"function":function(a){this.$main.call(this,{},a)},"object, function":function(a,b){this.$main.call(this,a,b)},$main:function(a,b){var c,d,e=this._collection,f=e.keys(),g=f.length;c=function(a){a?b&&b(a):(g--,0===g&&b&&b(!1))};for(d in e)e.hasOwnProperty(d)&&(a?e[d].loadCustom(a,c):e[d].load(c))}}),d.prototype.save=new l({"function":function(a){this.$main.call(this,{},a)},"object, function":function(a,b){this.$main.call(this,a,b)},$main:function(a,b){var c,d,e=this._collection,f=e.keys(),g=f.length;c=function(a){a?b&&b(a):(g--,0===g&&b&&b(!1))};for(d in e)e.hasOwnProperty(d)&&(a.custom?e[d].saveCustom(c):e[d].save(c))}}),m.finishModule("Persist"),b.exports=k},{"./Collection":4,"./CollectionGroup":5,"./PersistCompress":29,"./PersistCrypto":30,"./Shared":33,async:35,localforage:71}],29:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("pako"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){},d.mixin(f.prototype,"Mixin.Common"),f.prototype.encode=function(a,b,c){var d,f,g,h={data:a,type:"fdbCompress",enabled:!1};d=a.length,g=e.deflate(a,{to:"string"}),f=g.length,d>f&&(h.data=g,h.enabled=!0),b.compression={enabled:h.enabled,compressedBytes:f,uncompressedBytes:d,effect:Math.round(100/d*f)+"%"},c(!1,this.jStringify(h),b)},f.prototype.decode=function(a,b,c){var d,f=!1;a?(a=this.jParse(a),a.enabled?(d=e.inflate(a.data,{to:"string"}),f=!0):(d=a.data,f=!1),b.compression={enabled:f},c&&c(!1,d,b)):c&&c(!1,d,b)},d.plugins.FdbCompress=f,b.exports=f},{"./Shared":33,pako:72}],30:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("crypto-js"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){if(!a||!a.pass)throw'Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.';this._algo=a.algo||"AES",this._pass=a.pass},d.mixin(f.prototype,"Mixin.Common"),d.synthesize(f.prototype,"pass"),f.prototype.stringify=function(a){var b={ct:a.ciphertext.toString(e.enc.Base64)};return a.iv&&(b.iv=a.iv.toString()),a.salt&&(b.s=a.salt.toString()),this.jStringify(b)},f.prototype.parse=function(a){var b=this.jParse(a),c=e.lib.CipherParams.create({ciphertext:e.enc.Base64.parse(b.ct)});return b.iv&&(c.iv=e.enc.Hex.parse(b.iv)),b.s&&(c.salt=e.enc.Hex.parse(b.s)),c},f.prototype.encode=function(a,b,c){var d,f=this,g={type:"fdbCrypto" };d=e[this._algo].encrypt(a,this._pass,{format:{stringify:function(){return f.stringify.apply(f,arguments)},parse:function(){return f.parse.apply(f,arguments)}}}),g.data=d.toString(),g.enabled=!0,b.encryption={enabled:g.enabled},c&&c(!1,this.jStringify(g),b)},f.prototype.decode=function(a,b,c){var d,f=this;a?(a=this.jParse(a),d=e[this._algo].decrypt(a.data,this._pass,{format:{stringify:function(){return f.stringify.apply(f,arguments)},parse:function(){return f.parse.apply(f,arguments)}}}).toString(e.enc.Utf8),c&&c(!1,d,b)):c&&c(!1,a,b)},d.plugins.FdbCrypto=f,b.exports=f},{"./Shared":33,"crypto-js":44}],31:[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":33}],32:[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){return new RegExp(a.source,a.params)})},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},{}],33:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.522",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":15,"./Mixin.ChainReactor":16,"./Mixin.Common":17,"./Mixin.Constants":18,"./Mixin.Events":19,"./Mixin.Matching":20,"./Mixin.Sorting":21,"./Mixin.Tags":22,"./Mixin.Triggers":23,"./Mixin.Updating":24,"./Overload":26}],34:[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={}},{}],35:[function(a,b,c){(function(a,c){!function(){function d(){}function e(a){return a}function f(a){return!!a}function g(a){return!a}function h(a){return function(){if(null===a)throw new Error("Callback was already called.");a.apply(this,arguments),a=null}}function i(a){return function(){null!==a&&(a.apply(this,arguments),a=null)}}function j(a){return N(a)||"number"==typeof a.length&&a.length>=0&&a.length%1===0}function k(a,b){for(var c=-1,d=a.length;++c<d;)b(a[c],c,a)}function l(a,b){for(var c=-1,d=a.length,e=Array(d);++c<d;)e[c]=b(a[c],c,a);return e}function m(a){return l(Array(a),function(a,b){return b})}function n(a,b,c){return k(a,function(a,d,e){c=b(c,a,d,e)}),c}function o(a,b){k(P(a),function(c){b(a[c],c)})}function p(a,b){for(var c=0;c<a.length;c++)if(a[c]===b)return c;return-1}function q(a){var b,c,d=-1;return j(a)?(b=a.length,function(){return d++,b>d?d:null}):(c=P(a),b=c.length,function(){return d++,b>d?c[d]:null})}function r(a,b){return b=null==b?a.length-1:+b,function(){for(var c=Math.max(arguments.length-b,0),d=Array(c),e=0;c>e;e++)d[e]=arguments[e+b];switch(b){case 0:return a.call(this,d);case 1:return a.call(this,arguments[0],d)}}}function s(a){return function(b,c,d){return a(b,d)}}function t(a){return function(b,c,e){e=i(e||d),b=b||[];var f=q(b);if(0>=a)return e(null);var g=!1,j=0,k=!1;!function l(){if(g&&0>=j)return e(null);for(;a>j&&!k;){var d=f();if(null===d)return g=!0,void(0>=j&&e(null));j+=1,c(b[d],d,h(function(a){j-=1,a?(e(a),k=!0):l()}))}}()}}function u(a){return function(b,c,d){return a(K.eachOf,b,c,d)}}function v(a){return function(b,c,d,e){return a(t(c),b,d,e)}}function w(a){return function(b,c,d){return a(K.eachOfSeries,b,c,d)}}function x(a,b,c,e){e=i(e||d),b=b||[];var f=j(b)?[]:{};a(b,function(a,b,d){c(a,function(a,c){f[b]=c,d(a)})},function(a){e(a,f)})}function y(a,b,c,d){var e=[];a(b,function(a,b,d){c(a,function(c){c&&e.push({index:b,value:a}),d()})},function(){d(l(e.sort(function(a,b){return a.index-b.index}),function(a){return a.value}))})}function z(a,b,c,d){y(a,b,function(a,b){c(a,function(a){b(!a)})},d)}function A(a,b,c){return function(d,e,f,g){function h(){g&&g(c(!1,void 0))}function i(a,d,e){return g?void f(a,function(d){g&&b(d)&&(g(c(!0,a)),g=f=!1),e()}):e()}arguments.length>3?a(d,e,i,h):(g=f,f=e,a(d,i,h))}}function B(a,b){return b}function C(a,b,c){c=c||d;var e=j(b)?[]:{};a(b,function(a,b,c){a(r(function(a,d){d.length<=1&&(d=d[0]),e[b]=d,c(a)}))},function(a){c(a,e)})}function D(a,b,c,d){var e=[];a(b,function(a,b,d){c(a,function(a,b){e=e.concat(b||[]),d(a)})},function(a){d(a,e)})}function E(a,b,c){function e(a,b,c,e){if(null!=e&&"function"!=typeof e)throw new Error("task callback must be a function");return a.started=!0,N(b)||(b=[b]),0===b.length&&a.idle()?K.setImmediate(function(){a.drain()}):(k(b,function(b){var f={data:b,callback:e||d};c?a.tasks.unshift(f):a.tasks.push(f),a.tasks.length===a.concurrency&&a.saturated()}),void K.setImmediate(a.process))}function f(a,b){return function(){g-=1;var c=!1,d=arguments;k(b,function(a){k(i,function(b,d){b!==a||c||(i.splice(d,1),c=!0)}),a.callback.apply(a,d)}),a.tasks.length+g===0&&a.drain(),a.process()}}if(null==b)b=1;else if(0===b)throw new Error("Concurrency must not be zero");var g=0,i=[],j={tasks:[],concurrency:b,payload:c,saturated:d,empty:d,drain:d,started:!1,paused:!1,push:function(a,b){e(j,a,!1,b)},kill:function(){j.drain=d,j.tasks=[]},unshift:function(a,b){e(j,a,!0,b)},process:function(){if(!j.paused&&g<j.concurrency&&j.tasks.length)for(;g<j.concurrency&&j.tasks.length;){var b=j.payload?j.tasks.splice(0,j.payload):j.tasks.splice(0,j.tasks.length),c=l(b,function(a){return a.data});0===j.tasks.length&&j.empty(),g+=1,i.push(b[0]);var d=h(f(j,b));a(c,d)}},length:function(){return j.tasks.length},running:function(){return g},workersList:function(){return i},idle:function(){return j.tasks.length+g===0},pause:function(){j.paused=!0},resume:function(){if(j.paused!==!1){j.paused=!1;for(var a=Math.min(j.concurrency,j.tasks.length),b=1;a>=b;b++)K.setImmediate(j.process)}}};return j}function F(a){return r(function(b,c){b.apply(null,c.concat([r(function(b,c){"object"==typeof console&&(b?console.error&&console.error(b):console[a]&&k(c,function(b){console[a](b)}))})]))})}function G(a){return function(b,c,d){a(m(b),c,d)}}function H(a){return r(function(b,c){var d=r(function(c){var d=this,e=c.pop();return a(b,function(a,b,e){a.apply(d,c.concat([e]))},e)});return c.length?d.apply(this,c):d})}function I(a){return r(function(b){var c=b.pop();b.push(function(){var a=arguments;d?K.setImmediate(function(){c.apply(null,a)}):c.apply(null,a)});var d=!0;a.apply(this,b),d=!1})}var J,K={},L="object"==typeof self&&self.self===self&&self||"object"==typeof c&&c.global===c&&c||this;null!=L&&(J=L.async),K.noConflict=function(){return L.async=J,K};var M=Object.prototype.toString,N=Array.isArray||function(a){return"[object Array]"===M.call(a)},O=function(a){var b=typeof a;return"function"===b||"object"===b&&!!a},P=Object.keys||function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(c);return b},Q="function"==typeof setImmediate&&setImmediate,R=Q?function(a){Q(a)}:function(a){setTimeout(a,0)};"object"==typeof a&&"function"==typeof a.nextTick?K.nextTick=a.nextTick:K.nextTick=R,K.setImmediate=Q?R:K.nextTick,K.forEach=K.each=function(a,b,c){return K.eachOf(a,s(b),c)},K.forEachSeries=K.eachSeries=function(a,b,c){return K.eachOfSeries(a,s(b),c)},K.forEachLimit=K.eachLimit=function(a,b,c,d){return t(b)(a,s(c),d)},K.forEachOf=K.eachOf=function(a,b,c){function e(a){j--,a?c(a):null===f&&0>=j&&c(null)}c=i(c||d),a=a||[];for(var f,g=q(a),j=0;null!=(f=g());)j+=1,b(a[f],f,h(e));0===j&&c(null)},K.forEachOfSeries=K.eachOfSeries=function(a,b,c){function e(){var d=!0;return null===g?c(null):(b(a[g],g,h(function(a){if(a)c(a);else{if(g=f(),null===g)return c(null);d?K.setImmediate(e):e()}})),void(d=!1))}c=i(c||d),a=a||[];var f=q(a),g=f();e()},K.forEachOfLimit=K.eachOfLimit=function(a,b,c,d){t(b)(a,c,d)},K.map=u(x),K.mapSeries=w(x),K.mapLimit=v(x),K.inject=K.foldl=K.reduce=function(a,b,c,d){K.eachOfSeries(a,function(a,d,e){c(b,a,function(a,c){b=c,e(a)})},function(a){d(a,b)})},K.foldr=K.reduceRight=function(a,b,c,d){var f=l(a,e).reverse();K.reduce(f,b,c,d)},K.transform=function(a,b,c,d){3===arguments.length&&(d=c,c=b,b=N(a)?[]:{}),K.eachOf(a,function(a,d,e){c(b,a,d,e)},function(a){d(a,b)})},K.select=K.filter=u(y),K.selectLimit=K.filterLimit=v(y),K.selectSeries=K.filterSeries=w(y),K.reject=u(z),K.rejectLimit=v(z),K.rejectSeries=w(z),K.any=K.some=A(K.eachOf,f,e),K.someLimit=A(K.eachOfLimit,f,e),K.all=K.every=A(K.eachOf,g,g),K.everyLimit=A(K.eachOfLimit,g,g),K.detect=A(K.eachOf,e,B),K.detectSeries=A(K.eachOfSeries,e,B),K.detectLimit=A(K.eachOfLimit,e,B),K.sortBy=function(a,b,c){function d(a,b){var c=a.criteria,d=b.criteria;return d>c?-1:c>d?1:0}K.map(a,function(a,c){b(a,function(b,d){b?c(b):c(null,{value:a,criteria:d})})},function(a,b){return a?c(a):void c(null,l(b.sort(d),function(a){return a.value}))})},K.auto=function(a,b,c){function e(a){q.unshift(a)}function f(a){var b=p(q,a);b>=0&&q.splice(b,1)}function g(){j--,k(q.slice(0),function(a){a()})}c||(c=b,b=null),c=i(c||d);var h=P(a),j=h.length;if(!j)return c(null);b||(b=j);var l={},m=0,q=[];e(function(){j||c(null,l)}),k(h,function(d){function h(){return b>m&&n(s,function(a,b){return a&&l.hasOwnProperty(b)},!0)&&!l.hasOwnProperty(d)}function i(){h()&&(m++,f(i),k[k.length-1](q,l))}for(var j,k=N(a[d])?a[d]:[a[d]],q=r(function(a,b){if(m--,b.length<=1&&(b=b[0]),a){var e={};o(l,function(a,b){e[b]=a}),e[d]=b,c(a,e)}else l[d]=b,K.setImmediate(g)}),s=k.slice(0,k.length-1),t=s.length;t--;){if(!(j=a[s[t]]))throw new Error("Has inexistant dependency");if(N(j)&&p(j,d)>=0)throw new Error("Has cyclic dependencies")}h()?(m++,k[k.length-1](q,l)):e(i)})},K.retry=function(a,b,c){function d(a,b){if("number"==typeof b)a.times=parseInt(b,10)||f;else{if("object"!=typeof b)throw new Error("Unsupported argument type for 'times': "+typeof b);a.times=parseInt(b.times,10)||f,a.interval=parseInt(b.interval,10)||g}}function e(a,b){function c(a,c){return function(d){a(function(a,b){d(!a||c,{err:a,result:b})},b)}}function d(a){return function(b){setTimeout(function(){b(null)},a)}}for(;i.times;){var e=!(i.times-=1);h.push(c(i.task,e)),!e&&i.interval>0&&h.push(d(i.interval))}K.series(h,function(b,c){c=c[c.length-1],(a||i.callback)(c.err,c.result)})}var f=5,g=0,h=[],i={times:f,interval:g},j=arguments.length;if(1>j||j>3)throw new Error("Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)");return 2>=j&&"function"==typeof a&&(c=b,b=a),"function"!=typeof a&&d(i,a),i.callback=c,i.task=b,i.callback?e():e},K.waterfall=function(a,b){function c(a){return r(function(d,e){if(d)b.apply(null,[d].concat(e));else{var f=a.next();f?e.push(c(f)):e.push(b),I(a).apply(null,e)}})}if(b=i(b||d),!N(a)){var e=new Error("First argument to waterfall must be an array of functions");return b(e)}return a.length?void c(K.iterator(a))():b()},K.parallel=function(a,b){C(K.eachOf,a,b)},K.parallelLimit=function(a,b,c){C(t(b),a,c)},K.series=function(a,b){C(K.eachOfSeries,a,b)},K.iterator=function(a){function b(c){function d(){return a.length&&a[c].apply(null,arguments),d.next()}return d.next=function(){return c<a.length-1?b(c+1):null},d}return b(0)},K.apply=r(function(a,b){return r(function(c){return a.apply(null,b.concat(c))})}),K.concat=u(D),K.concatSeries=w(D),K.whilst=function(a,b,c){if(c=c||d,a()){var e=r(function(d,f){d?c(d):a.apply(this,f)?b(e):c(null)});b(e)}else c(null)},K.doWhilst=function(a,b,c){var d=0;return K.whilst(function(){return++d<=1||b.apply(this,arguments)},a,c)},K.until=function(a,b,c){return K.whilst(function(){return!a.apply(this,arguments)},b,c)},K.doUntil=function(a,b,c){return K.doWhilst(a,function(){return!b.apply(this,arguments)},c)},K.during=function(a,b,c){c=c||d;var e=r(function(b,d){b?c(b):(d.push(f),a.apply(this,d))}),f=function(a,d){a?c(a):d?b(e):c(null)};a(f)},K.doDuring=function(a,b,c){var d=0;K.during(function(a){d++<1?a(null,!0):b.apply(this,arguments)},a,c)},K.queue=function(a,b){var c=E(function(b,c){a(b[0],c)},b,1);return c},K.priorityQueue=function(a,b){function c(a,b){return a.priority-b.priority}function e(a,b,c){for(var d=-1,e=a.length-1;e>d;){var f=d+(e-d+1>>>1);c(b,a[f])>=0?d=f:e=f-1}return d}function f(a,b,f,g){if(null!=g&&"function"!=typeof g)throw new Error("task callback must be a function");return a.started=!0,N(b)||(b=[b]),0===b.length?K.setImmediate(function(){a.drain()}):void k(b,function(b){var h={data:b,priority:f,callback:"function"==typeof g?g:d};a.tasks.splice(e(a.tasks,h,c)+1,0,h),a.tasks.length===a.concurrency&&a.saturated(),K.setImmediate(a.process)})}var g=K.queue(a,b);return g.push=function(a,b,c){f(g,a,b,c)},delete g.unshift,g},K.cargo=function(a,b){return E(a,1,b)},K.log=F("log"),K.dir=F("dir"),K.memoize=function(a,b){var c={},d={};b=b||e;var f=r(function(e){var f=e.pop(),g=b.apply(null,e);g in c?K.setImmediate(function(){f.apply(null,c[g])}):g in d?d[g].push(f):(d[g]=[f],a.apply(null,e.concat([r(function(a){c[g]=a;var b=d[g];delete d[g];for(var e=0,f=b.length;f>e;e++)b[e].apply(null,a)})])))});return f.memo=c,f.unmemoized=a,f},K.unmemoize=function(a){return function(){return(a.unmemoized||a).apply(null,arguments)}},K.times=G(K.map),K.timesSeries=G(K.mapSeries),K.timesLimit=function(a,b,c,d){return K.mapLimit(m(a),b,c,d)},K.seq=function(){var a=arguments;return r(function(b){var c=this,e=b[b.length-1];"function"==typeof e?b.pop():e=d,K.reduce(a,b,function(a,b,d){b.apply(c,a.concat([r(function(a,b){d(a,b)})]))},function(a,b){e.apply(c,[a].concat(b))})})},K.compose=function(){return K.seq.apply(null,Array.prototype.reverse.call(arguments))},K.applyEach=H(K.eachOf),K.applyEachSeries=H(K.eachOfSeries),K.forever=function(a,b){function c(a){return a?e(a):void f(c)}var e=h(b||d),f=I(a);c()},K.ensureAsync=I,K.constant=r(function(a){var b=[null].concat(a);return function(a){return a.apply(this,b)}}),K.wrapSync=K.asyncify=function(a){return r(function(b){var c,d=b.pop();try{c=a.apply(this,b)}catch(e){return d(e)}O(c)&&"function"==typeof c.then?c.then(function(a){d(null,a)})["catch"](function(a){d(a.message?a:new Error(a))}):d(null,c)})},"object"==typeof b&&b.exports?b.exports=K:"function"==typeof define&&define.amd?define([],function(){return K}):L.async=K}()}).call(this,a("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:70}],36:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.BlockCipher,e=b.algo,f=[],g=[],h=[],i=[],j=[],k=[],l=[],m=[],n=[],o=[];!function(){for(var a=[],b=0;256>b;b++)128>b?a[b]=b<<1:a[b]=b<<1^283;for(var c=0,d=0,b=0;256>b;b++){var e=d^d<<1^d<<2^d<<3^d<<4;e=e>>>8^255&e^99,f[c]=e,g[e]=c;var p=a[c],q=a[p],r=a[q],s=257*a[e]^16843008*e;h[c]=s<<24|s>>>8,i[c]=s<<16|s>>>16,j[c]=s<<8|s>>>24,k[c]=s;var s=16843009*r^65537*q^257*p^16843008*c;l[e]=s<<24|s>>>8,m[e]=s<<16|s>>>16,n[e]=s<<8|s>>>24,o[e]=s,c?(c=p^a[a[a[r^p]]],d^=a[a[d]]):c=d=1}}();var p=[0,1,2,4,8,16,32,64,128,27,54],q=e.AES=d.extend({_doReset:function(){for(var a=this._key,b=a.words,c=a.sigBytes/4,d=this._nRounds=c+6,e=4*(d+1),g=this._keySchedule=[],h=0;e>h;h++)if(c>h)g[h]=b[h];else{var i=g[h-1];h%c?c>6&&h%c==4&&(i=f[i>>>24]<<24|f[i>>>16&255]<<16|f[i>>>8&255]<<8|f[255&i]):(i=i<<8|i>>>24,i=f[i>>>24]<<24|f[i>>>16&255]<<16|f[i>>>8&255]<<8|f[255&i],i^=p[h/c|0]<<24),g[h]=g[h-c]^i}for(var j=this._invKeySchedule=[],k=0;e>k;k++){var h=e-k;if(k%4)var i=g[h];else var i=g[h-4];4>k||4>=h?j[k]=i:j[k]=l[f[i>>>24]]^m[f[i>>>16&255]]^n[f[i>>>8&255]]^o[f[255&i]]}},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._keySchedule,h,i,j,k,f)},decryptBlock:function(a,b){var c=a[b+1];a[b+1]=a[b+3],a[b+3]=c,this._doCryptBlock(a,b,this._invKeySchedule,l,m,n,o,g);var c=a[b+1];a[b+1]=a[b+3],a[b+3]=c},_doCryptBlock:function(a,b,c,d,e,f,g,h){for(var i=this._nRounds,j=a[b]^c[0],k=a[b+1]^c[1],l=a[b+2]^c[2],m=a[b+3]^c[3],n=4,o=1;i>o;o++){var p=d[j>>>24]^e[k>>>16&255]^f[l>>>8&255]^g[255&m]^c[n++],q=d[k>>>24]^e[l>>>16&255]^f[m>>>8&255]^g[255&j]^c[n++],r=d[l>>>24]^e[m>>>16&255]^f[j>>>8&255]^g[255&k]^c[n++],s=d[m>>>24]^e[j>>>16&255]^f[k>>>8&255]^g[255&l]^c[n++];j=p,k=q,l=r,m=s}var p=(h[j>>>24]<<24|h[k>>>16&255]<<16|h[l>>>8&255]<<8|h[255&m])^c[n++],q=(h[k>>>24]<<24|h[l>>>16&255]<<16|h[m>>>8&255]<<8|h[255&j])^c[n++],r=(h[l>>>24]<<24|h[m>>>16&255]<<16|h[j>>>8&255]<<8|h[255&k])^c[n++],s=(h[m>>>24]<<24|h[j>>>16&255]<<16|h[k>>>8&255]<<8|h[255&l])^c[n++];a[b]=p,a[b+1]=q,a[b+2]=r,a[b+3]=s},keySize:8});b.AES=d._createHelper(q)}(),a.AES})},{"./cipher-core":37,"./core":38,"./enc-base64":39,"./evpkdf":41,"./md5":46}],37:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){a.lib.Cipher||function(b){var c=a,d=c.lib,e=d.Base,f=d.WordArray,g=d.BufferedBlockAlgorithm,h=c.enc,i=(h.Utf8,h.Base64),j=c.algo,k=j.EvpKDF,l=d.Cipher=g.extend({cfg:e.extend(),createEncryptor:function(a,b){return this.create(this._ENC_XFORM_MODE,a,b)},createDecryptor:function(a,b){return this.create(this._DEC_XFORM_MODE,a,b)},init:function(a,b,c){this.cfg=this.cfg.extend(c),this._xformMode=a,this._key=b,this.reset()},reset:function(){g.reset.call(this),this._doReset()},process:function(a){return this._append(a),this._process()},finalize:function(a){a&&this._append(a);var b=this._doFinalize();return b},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function a(a){return"string"==typeof a?x:u}return function(b){return{encrypt:function(c,d,e){return a(d).encrypt(b,c,d,e)},decrypt:function(c,d,e){return a(d).decrypt(b,c,d,e)}}}}()}),m=(d.StreamCipher=l.extend({_doFinalize:function(){var a=this._process(!0);return a},blockSize:1}),c.mode={}),n=d.BlockCipherMode=e.extend({createEncryptor:function(a,b){return this.Encryptor.create(a,b)},createDecryptor:function(a,b){return this.Decryptor.create(a,b)},init:function(a,b){this._cipher=a,this._iv=b}}),o=m.CBC=function(){function a(a,c,d){var e=this._iv;if(e){var f=e;this._iv=b}else var f=this._prevBlock;for(var g=0;d>g;g++)a[c+g]^=f[g]}var c=n.extend();return c.Encryptor=c.extend({processBlock:function(b,c){var d=this._cipher,e=d.blockSize;a.call(this,b,c,e),d.encryptBlock(b,c),this._prevBlock=b.slice(c,c+e)}}),c.Decryptor=c.extend({processBlock:function(b,c){var d=this._cipher,e=d.blockSize,f=b.slice(c,c+e);d.decryptBlock(b,c),a.call(this,b,c,e),this._prevBlock=f}}),c}(),p=c.pad={},q=p.Pkcs7={pad:function(a,b){for(var c=4*b,d=c-a.sigBytes%c,e=d<<24|d<<16|d<<8|d,g=[],h=0;d>h;h+=4)g.push(e);var i=f.create(g,d);a.concat(i)},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},r=(d.BlockCipher=l.extend({cfg:l.cfg.extend({mode:o,padding:q}),reset:function(){l.reset.call(this);var a=this.cfg,b=a.iv,c=a.mode;if(this._xformMode==this._ENC_XFORM_MODE)var d=c.createEncryptor;else{var d=c.createDecryptor;this._minBufferSize=1}this._mode=d.call(c,this,b&&b.words)},_doProcessBlock:function(a,b){this._mode.processBlock(a,b)},_doFinalize:function(){var a=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){a.pad(this._data,this.blockSize);var b=this._process(!0)}else{var b=this._process(!0);a.unpad(b)}return b},blockSize:4}),d.CipherParams=e.extend({init:function(a){this.mixIn(a)},toString:function(a){return(a||this.formatter).stringify(this)}})),s=c.format={},t=s.OpenSSL={stringify:function(a){var b=a.ciphertext,c=a.salt;if(c)var d=f.create([1398893684,1701076831]).concat(c).concat(b);else var d=b;return d.toString(i)},parse:function(a){var b=i.parse(a),c=b.words;if(1398893684==c[0]&&1701076831==c[1]){var d=f.create(c.slice(2,4));c.splice(0,4),b.sigBytes-=16}return r.create({ciphertext:b,salt:d})}},u=d.SerializableCipher=e.extend({cfg:e.extend({format:t}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=a.createEncryptor(c,d),f=e.finalize(b),g=e.cfg;return r.create({ciphertext:f,key:c,iv:g.iv,algorithm:a,mode:g.mode,padding:g.padding,blockSize:a.blockSize,formatter:d.format})},decrypt:function(a,b,c,d){d=this.cfg.extend(d),b=this._parse(b,d.format);var e=a.createDecryptor(c,d).finalize(b.ciphertext);return e},_parse:function(a,b){return"string"==typeof a?b.parse(a,this):a}}),v=c.kdf={},w=v.OpenSSL={execute:function(a,b,c,d){d||(d=f.random(8));var e=k.create({keySize:b+c}).compute(a,d),g=f.create(e.words.slice(b),4*c);return e.sigBytes=4*b,r.create({key:e,iv:g,salt:d})}},x=d.PasswordBasedCipher=u.extend({cfg:u.cfg.extend({kdf:w}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=d.kdf.execute(c,a.keySize,a.ivSize);d.iv=e.iv;var f=u.encrypt.call(this,a,b,e.key,d);return f.mixIn(e),f},decrypt:function(a,b,c,d){d=this.cfg.extend(d),b=this._parse(b,d.format);var e=d.kdf.execute(c,a.keySize,a.ivSize,b.salt);d.iv=e.iv;var f=u.decrypt.call(this,a,b,e.key,d);return f}})}()})},{"./core":38}],38:[function(a,b,c){!function(a,d){"object"==typeof c?b.exports=c=d():"function"==typeof define&&define.amd?define([],d):a.CryptoJS=d()}(this,function(){var a=a||function(a,b){var c={},d=c.lib={},e=d.Base=function(){function a(){}return{extend:function(b){a.prototype=this;var c=new a;return b&&c.mixIn(b),c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)}),c.init.prototype=c,c.$super=this,c},create:function(){var a=this.extend();return a.init.apply(a,arguments),a},init:function(){},mixIn:function(a){for(var b in a)a.hasOwnProperty(b)&&(this[b]=a[b]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),f=d.WordArray=e.extend({init:function(a,c){a=this.words=a||[],c!=b?this.sigBytes=c:this.sigBytes=4*a.length},toString:function(a){return(a||h).stringify(this)},concat:function(a){var b=this.words,c=a.words,d=this.sigBytes,e=a.sigBytes;if(this.clamp(),d%4)for(var f=0;e>f;f++){var g=c[f>>>2]>>>24-f%4*8&255;b[d+f>>>2]|=g<<24-(d+f)%4*8}else for(var f=0;e>f;f+=4)b[d+f>>>2]=c[f>>>2];return this.sigBytes+=e,this},clamp:function(){var b=this.words,c=this.sigBytes;b[c>>>2]&=4294967295<<32-c%4*8,b.length=a.ceil(c/4)},clone:function(){var a=e.clone.call(this);return a.words=this.words.slice(0),a},random:function(b){for(var c,d=[],e=function(b){var b=b,c=987654321,d=4294967295;return function(){c=36969*(65535&c)+(c>>16)&d,b=18e3*(65535&b)+(b>>16)&d;var e=(c<<16)+b&d;return e/=4294967296,e+=.5,e*(a.random()>.5?1:-1)}},g=0;b>g;g+=4){var h=e(4294967296*(c||a.random()));c=987654071*h(),d.push(4294967296*h()|0)}return new f.init(d,b)}}),g=c.enc={},h=g.Hex={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e++){var f=b[e>>>2]>>>24-e%4*8&255;d.push((f>>>4).toString(16)),d.push((15&f).toString(16))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d+=2)c[d>>>3]|=parseInt(a.substr(d,2),16)<<24-d%8*4;return new f.init(c,b/2)}},i=g.Latin1={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e++){var f=b[e>>>2]>>>24-e%4*8&255;d.push(String.fromCharCode(f))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d++)c[d>>>2]|=(255&a.charCodeAt(d))<<24-d%4*8;return new f.init(c,b)}},j=g.Utf8={stringify:function(a){try{return decodeURIComponent(escape(i.stringify(a)))}catch(b){throw new Error("Malformed UTF-8 data")}},parse:function(a){return i.parse(unescape(encodeURIComponent(a)))}},k=d.BufferedBlockAlgorithm=e.extend({reset:function(){this._data=new f.init,this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=j.parse(a)),this._data.concat(a),this._nDataBytes+=a.sigBytes},_process:function(b){var c=this._data,d=c.words,e=c.sigBytes,g=this.blockSize,h=4*g,i=e/h;i=b?a.ceil(i):a.max((0|i)-this._minBufferSize,0);var j=i*g,k=a.min(4*j,e);if(j){for(var l=0;j>l;l+=g)this._doProcessBlock(d,l);var m=d.splice(0,j);c.sigBytes-=k}return new f.init(m,k)},clone:function(){var a=e.clone.call(this);return a._data=this._data.clone(),a},_minBufferSize:0}),l=(d.Hasher=k.extend({cfg:e.extend(),init:function(a){this.cfg=this.cfg.extend(a),this.reset()},reset:function(){k.reset.call(this),this._doReset()},update:function(a){return this._append(a),this._process(),this},finalize:function(a){a&&this._append(a);var b=this._doFinalize();return b},blockSize:16,_createHelper:function(a){return function(b,c){return new a.init(c).finalize(b)}},_createHmacHelper:function(a){return function(b,c){return new l.HMAC.init(a,c).finalize(b)}}}),c.algo={});return c}(Math);return a})},{}],39:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=b.enc;e.Base64={stringify:function(a){var b=a.words,c=a.sigBytes,d=this._map;a.clamp();for(var e=[],f=0;c>f;f+=3)for(var g=b[f>>>2]>>>24-f%4*8&255,h=b[f+1>>>2]>>>24-(f+1)%4*8&255,i=b[f+2>>>2]>>>24-(f+2)%4*8&255,j=g<<16|h<<8|i,k=0;4>k&&c>f+.75*k;k++)e.push(d.charAt(j>>>6*(3-k)&63));var l=d.charAt(64);if(l)for(;e.length%4;)e.push(l);return e.join("")},parse:function(a){var b=a.length,c=this._map,e=c.charAt(64);if(e){var f=a.indexOf(e);-1!=f&&(b=f)}for(var g=[],h=0,i=0;b>i;i++)if(i%4){var j=c.indexOf(a.charAt(i-1))<<i%4*2,k=c.indexOf(a.charAt(i))>>>6-i%4*2;g[h>>>2]|=(j|k)<<24-h%4*8,h++}return d.create(g,h)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),a.enc.Base64})},{"./core":38}],40:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a){return a<<8&4278255360|a>>>8&16711935}var c=a,d=c.lib,e=d.WordArray,f=c.enc;f.Utf16=f.Utf16BE={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e+=2){var f=b[e>>>2]>>>16-e%4*8&65535;d.push(String.fromCharCode(f))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d++)c[d>>>1]|=a.charCodeAt(d)<<16-d%2*16;return e.create(c,2*b)}};f.Utf16LE={stringify:function(a){for(var c=a.words,d=a.sigBytes,e=[],f=0;d>f;f+=2){var g=b(c[f>>>2]>>>16-f%4*8&65535);e.push(String.fromCharCode(g))}return e.join("")},parse:function(a){for(var c=a.length,d=[],f=0;c>f;f++)d[f>>>1]|=b(a.charCodeAt(f)<<16-f%2*16);return e.create(d,2*c)}}}(),a.enc.Utf16})},{"./core":38}],41:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha1"),a("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.Base,e=c.WordArray,f=b.algo,g=f.MD5,h=f.EvpKDF=d.extend({cfg:d.extend({keySize:4,hasher:g,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,d=c.hasher.create(),f=e.create(),g=f.words,h=c.keySize,i=c.iterations;g.length<h;){j&&d.update(j);var j=d.update(a).finalize(b);d.reset();for(var k=1;i>k;k++)j=d.finalize(j),d.reset();f.concat(j)}return f.sigBytes=4*h,f}});b.EvpKDF=function(a,b,c){return h.create(c).compute(a,b)}}(),a.EvpKDF})},{"./core":38,"./hmac":43,"./sha1":62}],42:[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":37,"./core":38}],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){!function(){var b=a,c=b.lib,d=c.Base,e=b.enc,f=e.Utf8,g=b.algo;g.HMAC=d.extend({init:function(a,b){a=this._hasher=new a.init,"string"==typeof b&&(b=f.parse(b)); var c=a.blockSize,d=4*c;b.sigBytes>d&&(b=a.finalize(b)),b.clamp();for(var e=this._oKey=b.clone(),g=this._iKey=b.clone(),h=e.words,i=g.words,j=0;c>j;j++)h[j]^=1549556828,i[j]^=909522486;e.sigBytes=g.sigBytes=d,this.reset()},reset:function(){var a=this._hasher;a.reset(),a.update(this._iKey)},update:function(a){return this._hasher.update(a),this},finalize:function(a){var b=this._hasher,c=b.finalize(a);b.reset();var d=b.finalize(this._oKey.clone().concat(c));return d}})}()})},{"./core":38}],44:[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":36,"./cipher-core":37,"./core":38,"./enc-base64":39,"./enc-utf16":40,"./evpkdf":41,"./format-hex":42,"./hmac":43,"./lib-typedarrays":45,"./md5":46,"./mode-cfb":47,"./mode-ctr":49,"./mode-ctr-gladman":48,"./mode-ecb":50,"./mode-ofb":51,"./pad-ansix923":52,"./pad-iso10126":53,"./pad-iso97971":54,"./pad-nopadding":55,"./pad-zeropadding":56,"./pbkdf2":57,"./rabbit":59,"./rabbit-legacy":58,"./rc4":60,"./ripemd160":61,"./sha1":62,"./sha224":63,"./sha256":64,"./sha3":65,"./sha384":66,"./sha512":67,"./tripledes":68,"./x64-core":69}],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(){if("function"==typeof ArrayBuffer){var b=a,c=b.lib,d=c.WordArray,e=d.init,f=d.init=function(a){if(a instanceof ArrayBuffer&&(a=new Uint8Array(a)),(a instanceof Int8Array||"undefined"!=typeof Uint8ClampedArray&&a instanceof Uint8ClampedArray||a instanceof Int16Array||a instanceof Uint16Array||a instanceof Int32Array||a instanceof Uint32Array||a instanceof Float32Array||a instanceof Float64Array)&&(a=new Uint8Array(a.buffer,a.byteOffset,a.byteLength)),a instanceof Uint8Array){for(var b=a.byteLength,c=[],d=0;b>d;d++)c[d>>>2]|=a[d]<<24-d%4*8;e.call(this,c,b)}else e.apply(this,arguments)};f.prototype=d}}(),a.lib.WordArray})},{"./core":38}],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(b){function c(a,b,c,d,e,f,g){var h=a+(b&c|~b&d)+e+g;return(h<<f|h>>>32-f)+b}function d(a,b,c,d,e,f,g){var h=a+(b&d|c&~d)+e+g;return(h<<f|h>>>32-f)+b}function e(a,b,c,d,e,f,g){var h=a+(b^c^d)+e+g;return(h<<f|h>>>32-f)+b}function f(a,b,c,d,e,f,g){var h=a+(c^(b|~d))+e+g;return(h<<f|h>>>32-f)+b}var g=a,h=g.lib,i=h.WordArray,j=h.Hasher,k=g.algo,l=[];!function(){for(var a=0;64>a;a++)l[a]=4294967296*b.abs(b.sin(a+1))|0}();var m=k.MD5=j.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(a,b){for(var g=0;16>g;g++){var h=b+g,i=a[h];a[h]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8)}var j=this._hash.words,k=a[b+0],m=a[b+1],n=a[b+2],o=a[b+3],p=a[b+4],q=a[b+5],r=a[b+6],s=a[b+7],t=a[b+8],u=a[b+9],v=a[b+10],w=a[b+11],x=a[b+12],y=a[b+13],z=a[b+14],A=a[b+15],B=j[0],C=j[1],D=j[2],E=j[3];B=c(B,C,D,E,k,7,l[0]),E=c(E,B,C,D,m,12,l[1]),D=c(D,E,B,C,n,17,l[2]),C=c(C,D,E,B,o,22,l[3]),B=c(B,C,D,E,p,7,l[4]),E=c(E,B,C,D,q,12,l[5]),D=c(D,E,B,C,r,17,l[6]),C=c(C,D,E,B,s,22,l[7]),B=c(B,C,D,E,t,7,l[8]),E=c(E,B,C,D,u,12,l[9]),D=c(D,E,B,C,v,17,l[10]),C=c(C,D,E,B,w,22,l[11]),B=c(B,C,D,E,x,7,l[12]),E=c(E,B,C,D,y,12,l[13]),D=c(D,E,B,C,z,17,l[14]),C=c(C,D,E,B,A,22,l[15]),B=d(B,C,D,E,m,5,l[16]),E=d(E,B,C,D,r,9,l[17]),D=d(D,E,B,C,w,14,l[18]),C=d(C,D,E,B,k,20,l[19]),B=d(B,C,D,E,q,5,l[20]),E=d(E,B,C,D,v,9,l[21]),D=d(D,E,B,C,A,14,l[22]),C=d(C,D,E,B,p,20,l[23]),B=d(B,C,D,E,u,5,l[24]),E=d(E,B,C,D,z,9,l[25]),D=d(D,E,B,C,o,14,l[26]),C=d(C,D,E,B,t,20,l[27]),B=d(B,C,D,E,y,5,l[28]),E=d(E,B,C,D,n,9,l[29]),D=d(D,E,B,C,s,14,l[30]),C=d(C,D,E,B,x,20,l[31]),B=e(B,C,D,E,q,4,l[32]),E=e(E,B,C,D,t,11,l[33]),D=e(D,E,B,C,w,16,l[34]),C=e(C,D,E,B,z,23,l[35]),B=e(B,C,D,E,m,4,l[36]),E=e(E,B,C,D,p,11,l[37]),D=e(D,E,B,C,s,16,l[38]),C=e(C,D,E,B,v,23,l[39]),B=e(B,C,D,E,y,4,l[40]),E=e(E,B,C,D,k,11,l[41]),D=e(D,E,B,C,o,16,l[42]),C=e(C,D,E,B,r,23,l[43]),B=e(B,C,D,E,u,4,l[44]),E=e(E,B,C,D,x,11,l[45]),D=e(D,E,B,C,A,16,l[46]),C=e(C,D,E,B,n,23,l[47]),B=f(B,C,D,E,k,6,l[48]),E=f(E,B,C,D,s,10,l[49]),D=f(D,E,B,C,z,15,l[50]),C=f(C,D,E,B,q,21,l[51]),B=f(B,C,D,E,x,6,l[52]),E=f(E,B,C,D,o,10,l[53]),D=f(D,E,B,C,v,15,l[54]),C=f(C,D,E,B,m,21,l[55]),B=f(B,C,D,E,t,6,l[56]),E=f(E,B,C,D,A,10,l[57]),D=f(D,E,B,C,r,15,l[58]),C=f(C,D,E,B,y,21,l[59]),B=f(B,C,D,E,p,6,l[60]),E=f(E,B,C,D,w,10,l[61]),D=f(D,E,B,C,n,15,l[62]),C=f(C,D,E,B,u,21,l[63]),j[0]=j[0]+B|0,j[1]=j[1]+C|0,j[2]=j[2]+D|0,j[3]=j[3]+E|0},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,e=8*a.sigBytes;c[e>>>5]|=128<<24-e%32;var f=b.floor(d/4294967296),g=d;c[(e+64>>>9<<4)+15]=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),c[(e+64>>>9<<4)+14]=16711935&(g<<8|g>>>24)|4278255360&(g<<24|g>>>8),a.sigBytes=4*(c.length+1),this._process();for(var h=this._hash,i=h.words,j=0;4>j;j++){var k=i[j];i[j]=16711935&(k<<8|k>>>24)|4278255360&(k<<24|k>>>8)}return h},clone:function(){var a=j.clone.call(this);return a._hash=this._hash.clone(),a}});g.MD5=j._createHelper(m),g.HmacMD5=j._createHmacHelper(m)}(Math),a.MD5})},{"./core":38}],47:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CFB=function(){function b(a,b,c,d){var e=this._iv;if(e){var f=e.slice(0);this._iv=void 0}else var f=this._prevBlock;d.encryptBlock(f,0);for(var g=0;c>g;g++)a[b+g]^=f[g]}var c=a.lib.BlockCipherMode.extend();return c.Encryptor=c.extend({processBlock:function(a,c){var d=this._cipher,e=d.blockSize;b.call(this,a,c,e,d),this._prevBlock=a.slice(c,c+e)}}),c.Decryptor=c.extend({processBlock:function(a,c){var d=this._cipher,e=d.blockSize,f=a.slice(c,c+e);b.call(this,a,c,e,d),this._prevBlock=f}}),c}(),a.mode.CFB})},{"./cipher-core":37,"./core":38}],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 a.mode.CTRGladman=function(){function b(a){if(255===(a>>24&255)){var b=a>>16&255,c=a>>8&255,d=255&a;255===b?(b=0,255===c?(c=0,255===d?d=0:++d):++c):++b,a=0,a+=b<<16,a+=c<<8,a+=d}else a+=1<<24;return a}function c(a){return 0===(a[0]=b(a[0]))&&(a[1]=b(a[1])),a}var d=a.lib.BlockCipherMode.extend(),e=d.Encryptor=d.extend({processBlock:function(a,b){var d=this._cipher,e=d.blockSize,f=this._iv,g=this._counter;f&&(g=this._counter=f.slice(0),this._iv=void 0),c(g);var h=g.slice(0);d.encryptBlock(h,0);for(var i=0;e>i;i++)a[b+i]^=h[i]}});return d.Decryptor=e,d}(),a.mode.CTRGladman})},{"./cipher-core":37,"./core":38}],49:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CTR=function(){var b=a.lib.BlockCipherMode.extend(),c=b.Encryptor=b.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=this._iv,f=this._counter;e&&(f=this._counter=e.slice(0),this._iv=void 0);var g=f.slice(0);c.encryptBlock(g,0),f[d-1]=f[d-1]+1|0;for(var h=0;d>h;h++)a[b+h]^=g[h]}});return b.Decryptor=c,b}(),a.mode.CTR})},{"./cipher-core":37,"./core":38}],50:[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":37,"./core":38}],51:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.OFB=function(){var b=a.lib.BlockCipherMode.extend(),c=b.Encryptor=b.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=this._iv,f=this._keystream;e&&(f=this._keystream=e.slice(0),this._iv=void 0),c.encryptBlock(f,0);for(var g=0;d>g;g++)a[b+g]^=f[g]}});return b.Decryptor=c,b}(),a.mode.OFB})},{"./cipher-core":37,"./core":38}],52:[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":37,"./core":38}],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.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":37,"./core":38}],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.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":37,"./core":38}],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.pad.NoPadding={pad:function(){},unpad:function(){}},a.pad.NoPadding})},{"./cipher-core":37,"./core":38}],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.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":37,"./core":38}],57:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha1"),a("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.Base,e=c.WordArray,f=b.algo,g=f.SHA1,h=f.HMAC,i=f.PBKDF2=d.extend({cfg:d.extend({keySize:4,hasher:g,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,d=h.create(c.hasher,a),f=e.create(),g=e.create([1]),i=f.words,j=g.words,k=c.keySize,l=c.iterations;i.length<k;){var m=d.update(b).finalize(g);d.reset();for(var n=m.words,o=n.length,p=m,q=1;l>q;q++){p=d.finalize(p),d.reset();for(var r=p.words,s=0;o>s;s++)n[s]^=r[s]}f.concat(m),j[0]++}return f.sigBytes=4*k,f}});b.PBKDF2=function(a,b,c){return i.create(c).compute(a,b)}}(),a.PBKDF2})},{"./core":38,"./hmac":43,"./sha1":62}],58:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._X,b=this._C,c=0;8>c;c++)h[c]=b[c];b[0]=b[0]+1295307597+this._b|0,b[1]=b[1]+3545052371+(b[0]>>>0<h[0]>>>0?1:0)|0,b[2]=b[2]+886263092+(b[1]>>>0<h[1]>>>0?1:0)|0,b[3]=b[3]+1295307597+(b[2]>>>0<h[2]>>>0?1:0)|0,b[4]=b[4]+3545052371+(b[3]>>>0<h[3]>>>0?1:0)|0,b[5]=b[5]+886263092+(b[4]>>>0<h[4]>>>0?1:0)|0,b[6]=b[6]+1295307597+(b[5]>>>0<h[5]>>>0?1:0)|0,b[7]=b[7]+3545052371+(b[6]>>>0<h[6]>>>0?1:0)|0,this._b=b[7]>>>0<h[7]>>>0?1:0;for(var c=0;8>c;c++){var d=a[c]+b[c],e=65535&d,f=d>>>16,g=((e*e>>>17)+e*f>>>15)+f*f,j=((4294901760&d)*d|0)+((65535&d)*d|0);i[c]=g^j}a[0]=i[0]+(i[7]<<16|i[7]>>>16)+(i[6]<<16|i[6]>>>16)|0,a[1]=i[1]+(i[0]<<8|i[0]>>>24)+i[7]|0,a[2]=i[2]+(i[1]<<16|i[1]>>>16)+(i[0]<<16|i[0]>>>16)|0,a[3]=i[3]+(i[2]<<8|i[2]>>>24)+i[1]|0,a[4]=i[4]+(i[3]<<16|i[3]>>>16)+(i[2]<<16|i[2]>>>16)|0,a[5]=i[5]+(i[4]<<8|i[4]>>>24)+i[3]|0,a[6]=i[6]+(i[5]<<16|i[5]>>>16)+(i[4]<<16|i[4]>>>16)|0,a[7]=i[7]+(i[6]<<8|i[6]>>>24)+i[5]|0}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=[],h=[],i=[],j=f.RabbitLegacy=e.extend({_doReset:function(){var a=this._key.words,c=this.cfg.iv,d=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],e=this._C=[a[2]<<16|a[2]>>>16,4294901760&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,4294901760&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,4294901760&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,4294901760&a[3]|65535&a[0]];this._b=0;for(var f=0;4>f;f++)b.call(this);for(var f=0;8>f;f++)e[f]^=d[f+4&7];if(c){var g=c.words,h=g[0],i=g[1],j=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8),k=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),l=j>>>16|4294901760&k,m=k<<16|65535&j;e[0]^=j,e[1]^=l,e[2]^=k,e[3]^=m,e[4]^=j,e[5]^=l,e[6]^=k,e[7]^=m;for(var f=0;4>f;f++)b.call(this)}},_doProcessBlock:function(a,c){var d=this._X;b.call(this),g[0]=d[0]^d[5]>>>16^d[3]<<16,g[1]=d[2]^d[7]>>>16^d[5]<<16,g[2]=d[4]^d[1]>>>16^d[7]<<16,g[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;4>e;e++)g[e]=16711935&(g[e]<<8|g[e]>>>24)|4278255360&(g[e]<<24|g[e]>>>8),a[c+e]^=g[e]},blockSize:4,ivSize:2});c.RabbitLegacy=e._createHelper(j)}(),a.RabbitLegacy})},{"./cipher-core":37,"./core":38,"./enc-base64":39,"./evpkdf":41,"./md5":46}],59:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._X,b=this._C,c=0;8>c;c++)h[c]=b[c];b[0]=b[0]+1295307597+this._b|0,b[1]=b[1]+3545052371+(b[0]>>>0<h[0]>>>0?1:0)|0,b[2]=b[2]+886263092+(b[1]>>>0<h[1]>>>0?1:0)|0,b[3]=b[3]+1295307597+(b[2]>>>0<h[2]>>>0?1:0)|0,b[4]=b[4]+3545052371+(b[3]>>>0<h[3]>>>0?1:0)|0,b[5]=b[5]+886263092+(b[4]>>>0<h[4]>>>0?1:0)|0,b[6]=b[6]+1295307597+(b[5]>>>0<h[5]>>>0?1:0)|0,b[7]=b[7]+3545052371+(b[6]>>>0<h[6]>>>0?1:0)|0,this._b=b[7]>>>0<h[7]>>>0?1:0;for(var c=0;8>c;c++){var d=a[c]+b[c],e=65535&d,f=d>>>16,g=((e*e>>>17)+e*f>>>15)+f*f,j=((4294901760&d)*d|0)+((65535&d)*d|0);i[c]=g^j}a[0]=i[0]+(i[7]<<16|i[7]>>>16)+(i[6]<<16|i[6]>>>16)|0,a[1]=i[1]+(i[0]<<8|i[0]>>>24)+i[7]|0,a[2]=i[2]+(i[1]<<16|i[1]>>>16)+(i[0]<<16|i[0]>>>16)|0,a[3]=i[3]+(i[2]<<8|i[2]>>>24)+i[1]|0,a[4]=i[4]+(i[3]<<16|i[3]>>>16)+(i[2]<<16|i[2]>>>16)|0,a[5]=i[5]+(i[4]<<8|i[4]>>>24)+i[3]|0,a[6]=i[6]+(i[5]<<16|i[5]>>>16)+(i[4]<<16|i[4]>>>16)|0,a[7]=i[7]+(i[6]<<8|i[6]>>>24)+i[5]|0}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=[],h=[],i=[],j=f.Rabbit=e.extend({_doReset:function(){for(var a=this._key.words,c=this.cfg.iv,d=0;4>d;d++)a[d]=16711935&(a[d]<<8|a[d]>>>24)|4278255360&(a[d]<<24|a[d]>>>8);var e=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],f=this._C=[a[2]<<16|a[2]>>>16,4294901760&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,4294901760&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,4294901760&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,4294901760&a[3]|65535&a[0]];this._b=0;for(var d=0;4>d;d++)b.call(this);for(var d=0;8>d;d++)f[d]^=e[d+4&7];if(c){var g=c.words,h=g[0],i=g[1],j=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8),k=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),l=j>>>16|4294901760&k,m=k<<16|65535&j;f[0]^=j,f[1]^=l,f[2]^=k,f[3]^=m,f[4]^=j,f[5]^=l,f[6]^=k,f[7]^=m;for(var d=0;4>d;d++)b.call(this)}},_doProcessBlock:function(a,c){var d=this._X;b.call(this),g[0]=d[0]^d[5]>>>16^d[3]<<16,g[1]=d[2]^d[7]>>>16^d[5]<<16,g[2]=d[4]^d[1]>>>16^d[7]<<16,g[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;4>e;e++)g[e]=16711935&(g[e]<<8|g[e]>>>24)|4278255360&(g[e]<<24|g[e]>>>8),a[c+e]^=g[e]},blockSize:4,ivSize:2});c.Rabbit=e._createHelper(j)}(),a.Rabbit})},{"./cipher-core":37,"./core":38,"./enc-base64":39,"./evpkdf":41,"./md5":46}],60:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._S,b=this._i,c=this._j,d=0,e=0;4>e;e++){b=(b+1)%256,c=(c+a[b])%256;var f=a[b];a[b]=a[c],a[c]=f,d|=a[(a[b]+a[c])%256]<<24-8*e}return this._i=b,this._j=c,d}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=f.RC4=e.extend({_doReset:function(){for(var a=this._key,b=a.words,c=a.sigBytes,d=this._S=[],e=0;256>e;e++)d[e]=e;for(var e=0,f=0;256>e;e++){var g=e%c,h=b[g>>>2]>>>24-g%4*8&255;f=(f+d[e]+h)%256;var i=d[e];d[e]=d[f],d[f]=i}this._i=this._j=0},_doProcessBlock:function(a,c){a[c]^=b.call(this)},keySize:8,ivSize:0});c.RC4=e._createHelper(g);var h=f.RC4Drop=g.extend({cfg:g.cfg.extend({drop:192}),_doReset:function(){g._doReset.call(this);for(var a=this.cfg.drop;a>0;a--)b.call(this)}});c.RC4Drop=e._createHelper(h)}(),a.RC4})},{"./cipher-core":37,"./core":38,"./enc-base64":39,"./evpkdf":41,"./md5":46}],61:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){function c(a,b,c){return a^b^c}function d(a,b,c){return a&b|~a&c}function e(a,b,c){return(a|~b)^c}function f(a,b,c){return a&c|b&~c}function g(a,b,c){return a^(b|~c)}function h(a,b){return a<<b|a>>>32-b}var i=a,j=i.lib,k=j.WordArray,l=j.Hasher,m=i.algo,n=k.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),o=k.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),p=k.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),q=k.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),r=k.create([0,1518500249,1859775393,2400959708,2840853838]),s=k.create([1352829926,1548603684,1836072691,2053994217,0]),t=m.RIPEMD160=l.extend({_doReset:function(){this._hash=k.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(a,b){for(var i=0;16>i;i++){var j=b+i,k=a[j];a[j]=16711935&(k<<8|k>>>24)|4278255360&(k<<24|k>>>8)}var l,m,t,u,v,w,x,y,z,A,B=this._hash.words,C=r.words,D=s.words,E=n.words,F=o.words,G=p.words,H=q.words;w=l=B[0],x=m=B[1],y=t=B[2],z=u=B[3],A=v=B[4];for(var I,i=0;80>i;i+=1)I=l+a[b+E[i]]|0,I+=16>i?c(m,t,u)+C[0]:32>i?d(m,t,u)+C[1]:48>i?e(m,t,u)+C[2]:64>i?f(m,t,u)+C[3]:g(m,t,u)+C[4],I=0|I,I=h(I,G[i]),I=I+v|0,l=v,v=u,u=h(t,10),t=m,m=I,I=w+a[b+F[i]]|0,I+=16>i?g(x,y,z)+D[0]:32>i?f(x,y,z)+D[1]:48>i?e(x,y,z)+D[2]:64>i?d(x,y,z)+D[3]:c(x,y,z)+D[4],I=0|I,I=h(I,H[i]),I=I+A|0,w=A,A=z,z=h(y,10),y=x,x=I;I=B[1]+t+z|0,B[1]=B[2]+u+A|0,B[2]=B[3]+v+w|0,B[3]=B[4]+l+x|0,B[4]=B[0]+m+y|0,B[0]=I},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32,b[(d+64>>>9<<4)+14]=16711935&(c<<8|c>>>24)|4278255360&(c<<24|c>>>8),a.sigBytes=4*(b.length+1),this._process();for(var e=this._hash,f=e.words,g=0;5>g;g++){var h=f[g];f[g]=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8)}return e},clone:function(){var a=l.clone.call(this);return a._hash=this._hash.clone(),a}});i.RIPEMD160=l._createHelper(t),i.HmacRIPEMD160=l._createHmacHelper(t)}(Math),a.RIPEMD160})},{"./core":38}],62:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=c.Hasher,f=b.algo,g=[],h=f.SHA1=e.extend({_doReset:function(){this._hash=new d.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],h=c[3],i=c[4],j=0;80>j;j++){if(16>j)g[j]=0|a[b+j];else{var k=g[j-3]^g[j-8]^g[j-14]^g[j-16];g[j]=k<<1|k>>>31}var l=(d<<5|d>>>27)+i+g[j];l+=20>j?(e&f|~e&h)+1518500249:40>j?(e^f^h)+1859775393:60>j?(e&f|e&h|f&h)-1894007588:(e^f^h)-899497514,i=h,h=f,f=e<<30|e>>>2,e=d,d=l}c[0]=c[0]+d|0,c[1]=c[1]+e|0,c[2]=c[2]+f|0,c[3]=c[3]+h|0,c[4]=c[4]+i|0},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;return b[d>>>5]|=128<<24-d%32,b[(d+64>>>9<<4)+14]=Math.floor(c/4294967296),b[(d+64>>>9<<4)+15]=c,a.sigBytes=4*b.length,this._process(),this._hash},clone:function(){var a=e.clone.call(this);return a._hash=this._hash.clone(),a}});b.SHA1=e._createHelper(h),b.HmacSHA1=e._createHmacHelper(h)}(),a.SHA1})},{"./core":38}],63:[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":38,"./sha256":64}],64:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.WordArray,f=d.Hasher,g=c.algo,h=[],i=[];!function(){function a(a){for(var c=b.sqrt(a),d=2;c>=d;d++)if(!(a%d))return!1;return!0}function c(a){return 4294967296*(a-(0|a))|0}for(var d=2,e=0;64>e;)a(d)&&(8>e&&(h[e]=c(b.pow(d,.5))),i[e]=c(b.pow(d,1/3)),e++),d++}();var j=[],k=g.SHA256=f.extend({_doReset:function(){this._hash=new e.init(h.slice(0))},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],k=c[5],l=c[6],m=c[7],n=0;64>n;n++){if(16>n)j[n]=0|a[b+n];else{var o=j[n-15],p=(o<<25|o>>>7)^(o<<14|o>>>18)^o>>>3,q=j[n-2],r=(q<<15|q>>>17)^(q<<13|q>>>19)^q>>>10;j[n]=p+j[n-7]+r+j[n-16]}var s=h&k^~h&l,t=d&e^d&f^e&f,u=(d<<30|d>>>2)^(d<<19|d>>>13)^(d<<10|d>>>22),v=(h<<26|h>>>6)^(h<<21|h>>>11)^(h<<7|h>>>25),w=m+v+s+i[n]+j[n],x=u+t;m=l,l=k,k=h,h=g+w|0,g=f,f=e,e=d,d=w+x|0}c[0]=c[0]+d|0,c[1]=c[1]+e|0,c[2]=c[2]+f|0,c[3]=c[3]+g|0,c[4]=c[4]+h|0,c[5]=c[5]+k|0,c[6]=c[6]+l|0,c[7]=c[7]+m|0},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,e=8*a.sigBytes;return c[e>>>5]|=128<<24-e%32,c[(e+64>>>9<<4)+14]=b.floor(d/4294967296),c[(e+64>>>9<<4)+15]=d,a.sigBytes=4*c.length,this._process(),this._hash},clone:function(){var a=f.clone.call(this);return a._hash=this._hash.clone(),a}});c.SHA256=f._createHelper(k),c.HmacSHA256=f._createHmacHelper(k)}(Math),a.SHA256})},{"./core":38}],65:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core")):"function"==typeof define&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.WordArray,f=d.Hasher,g=c.x64,h=g.Word,i=c.algo,j=[],k=[],l=[];!function(){for(var a=1,b=0,c=0;24>c;c++){j[a+5*b]=(c+1)*(c+2)/2%64;var d=b%5,e=(2*a+3*b)%5;a=d,b=e}for(var a=0;5>a;a++)for(var b=0;5>b;b++)k[a+5*b]=b+(2*a+3*b)%5*5;for(var f=1,g=0;24>g;g++){for(var i=0,m=0,n=0;7>n;n++){if(1&f){var o=(1<<n)-1;32>o?m^=1<<o:i^=1<<o-32}128&f?f=f<<1^113:f<<=1}l[g]=h.create(i,m)}}();var m=[];!function(){for(var a=0;25>a;a++)m[a]=h.create()}();var n=i.SHA3=f.extend({cfg:f.cfg.extend({outputLength:512}),_doReset:function(){for(var a=this._state=[],b=0;25>b;b++)a[b]=new h.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(a,b){for(var c=this._state,d=this.blockSize/2,e=0;d>e;e++){var f=a[b+2*e],g=a[b+2*e+1];f=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),g=16711935&(g<<8|g>>>24)|4278255360&(g<<24|g>>>8);var h=c[e];h.high^=g,h.low^=f}for(var i=0;24>i;i++){for(var n=0;5>n;n++){for(var o=0,p=0,q=0;5>q;q++){var h=c[n+5*q];o^=h.high,p^=h.low}var r=m[n];r.high=o,r.low=p}for(var n=0;5>n;n++)for(var s=m[(n+4)%5],t=m[(n+1)%5],u=t.high,v=t.low,o=s.high^(u<<1|v>>>31),p=s.low^(v<<1|u>>>31),q=0;5>q;q++){var h=c[n+5*q];h.high^=o,h.low^=p}for(var w=1;25>w;w++){var h=c[w],x=h.high,y=h.low,z=j[w];if(32>z)var o=x<<z|y>>>32-z,p=y<<z|x>>>32-z;else var o=y<<z-32|x>>>64-z,p=x<<z-32|y>>>64-z;var A=m[k[w]];A.high=o,A.low=p}var B=m[0],C=c[0];B.high=C.high,B.low=C.low;for(var n=0;5>n;n++)for(var q=0;5>q;q++){var w=n+5*q,h=c[w],D=m[w],E=m[(n+1)%5+5*q],F=m[(n+2)%5+5*q];h.high=D.high^~E.high&F.high,h.low=D.low^~E.low&F.low}var h=c[0],G=l[i];h.high^=G.high,h.low^=G.low}},_doFinalize:function(){var a=this._data,c=a.words,d=(8*this._nDataBytes,8*a.sigBytes),f=32*this.blockSize;c[d>>>5]|=1<<24-d%32,c[(b.ceil((d+1)/f)*f>>>5)-1]|=128,a.sigBytes=4*c.length,this._process();for(var g=this._state,h=this.cfg.outputLength/8,i=h/8,j=[],k=0;i>k;k++){var l=g[k],m=l.high,n=l.low;m=16711935&(m<<8|m>>>24)|4278255360&(m<<24|m>>>8),n=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),j.push(n),j.push(m)}return new e.init(j,h)},clone:function(){for(var a=f.clone.call(this),b=a._state=this._state.slice(0),c=0;25>c;c++)b[c]=b[c].clone();return a}});c.SHA3=f._createHelper(n),c.HmacSHA3=f._createHmacHelper(n)}(Math),a.SHA3})},{"./core":38,"./x64-core":69}],66:[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":38,"./sha512":67,"./x64-core":69}],67:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core")):"function"==typeof define&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){return g.create.apply(g,arguments)}var c=a,d=c.lib,e=d.Hasher,f=c.x64,g=f.Word,h=f.WordArray,i=c.algo,j=[b(1116352408,3609767458),b(1899447441,602891725),b(3049323471,3964484399),b(3921009573,2173295548),b(961987163,4081628472),b(1508970993,3053834265),b(2453635748,2937671579),b(2870763221,3664609560),b(3624381080,2734883394),b(310598401,1164996542),b(607225278,1323610764),b(1426881987,3590304994),b(1925078388,4068182383),b(2162078206,991336113),b(2614888103,633803317),b(3248222580,3479774868),b(3835390401,2666613458),b(4022224774,944711139),b(264347078,2341262773),b(604807628,2007800933),b(770255983,1495990901),b(1249150122,1856431235),b(1555081692,3175218132),b(1996064986,2198950837),b(2554220882,3999719339),b(2821834349,766784016),b(2952996808,2566594879),b(3210313671,3203337956),b(3336571891,1034457026),b(3584528711,2466948901),b(113926993,3758326383),b(338241895,168717936),b(666307205,1188179964),b(773529912,1546045734),b(1294757372,1522805485),b(1396182291,2643833823),b(1695183700,2343527390),b(1986661051,1014477480),b(2177026350,1206759142),b(2456956037,344077627),b(2730485921,1290863460),b(2820302411,3158454273),b(3259730800,3505952657),b(3345764771,106217008),b(3516065817,3606008344),b(3600352804,1432725776),b(4094571909,1467031594),b(275423344,851169720),b(430227734,3100823752),b(506948616,1363258195),b(659060556,3750685593),b(883997877,3785050280),b(958139571,3318307427),b(1322822218,3812723403),b(1537002063,2003034995),b(1747873779,3602036899),b(1955562222,1575990012),b(2024104815,1125592928),b(2227730452,2716904306),b(2361852424,442776044),b(2428436474,593698344),b(2756734187,3733110249),b(3204031479,2999351573),b(3329325298,3815920427),b(3391569614,3928383900),b(3515267271,566280711),b(3940187606,3454069534),b(4118630271,4000239992),b(116418474,1914138554),b(174292421,2731055270),b(289380356,3203993006),b(460393269,320620315),b(685471733,587496836),b(852142971,1086792851),b(1017036298,365543100),b(1126000580,2618297676),b(1288033470,3409855158),b(1501505948,4234509866),b(1607167915,987167468),b(1816402316,1246189591)],k=[];!function(){for(var a=0;80>a;a++)k[a]=b()}();var l=i.SHA512=e.extend({_doReset:function(){this._hash=new h.init([new g.init(1779033703,4089235720),new g.init(3144134277,2227873595),new g.init(1013904242,4271175723),new g.init(2773480762,1595750129),new g.init(1359893119,2917565137),new g.init(2600822924,725511199),new g.init(528734635,4215389547),new g.init(1541459225,327033209)])},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],i=c[5],l=c[6],m=c[7],n=d.high,o=d.low,p=e.high,q=e.low,r=f.high,s=f.low,t=g.high,u=g.low,v=h.high,w=h.low,x=i.high,y=i.low,z=l.high,A=l.low,B=m.high,C=m.low,D=n,E=o,F=p,G=q,H=r,I=s,J=t,K=u,L=v,M=w,N=x,O=y,P=z,Q=A,R=B,S=C,T=0;80>T;T++){var U=k[T];if(16>T)var V=U.high=0|a[b+2*T],W=U.low=0|a[b+2*T+1];else{var X=k[T-15],Y=X.high,Z=X.low,$=(Y>>>1|Z<<31)^(Y>>>8|Z<<24)^Y>>>7,_=(Z>>>1|Y<<31)^(Z>>>8|Y<<24)^(Z>>>7|Y<<25),aa=k[T-2],ba=aa.high,ca=aa.low,da=(ba>>>19|ca<<13)^(ba<<3|ca>>>29)^ba>>>6,ea=(ca>>>19|ba<<13)^(ca<<3|ba>>>29)^(ca>>>6|ba<<26),fa=k[T-7],ga=fa.high,ha=fa.low,ia=k[T-16],ja=ia.high,ka=ia.low,W=_+ha,V=$+ga+(_>>>0>W>>>0?1:0),W=W+ea,V=V+da+(ea>>>0>W>>>0?1:0),W=W+ka,V=V+ja+(ka>>>0>W>>>0?1:0);U.high=V,U.low=W}var la=L&N^~L&P,ma=M&O^~M&Q,na=D&F^D&H^F&H,oa=E&G^E&I^G&I,pa=(D>>>28|E<<4)^(D<<30|E>>>2)^(D<<25|E>>>7),qa=(E>>>28|D<<4)^(E<<30|D>>>2)^(E<<25|D>>>7),ra=(L>>>14|M<<18)^(L>>>18|M<<14)^(L<<23|M>>>9),sa=(M>>>14|L<<18)^(M>>>18|L<<14)^(M<<23|L>>>9),ta=j[T],ua=ta.high,va=ta.low,wa=S+sa,xa=R+ra+(S>>>0>wa>>>0?1:0),wa=wa+ma,xa=xa+la+(ma>>>0>wa>>>0?1:0),wa=wa+va,xa=xa+ua+(va>>>0>wa>>>0?1:0),wa=wa+W,xa=xa+V+(W>>>0>wa>>>0?1:0),ya=qa+oa,za=pa+na+(qa>>>0>ya>>>0?1:0); R=P,S=Q,P=N,Q=O,N=L,O=M,M=K+wa|0,L=J+xa+(K>>>0>M>>>0?1:0)|0,J=H,K=I,H=F,I=G,F=D,G=E,E=wa+ya|0,D=xa+za+(wa>>>0>E>>>0?1:0)|0}o=d.low=o+E,d.high=n+D+(E>>>0>o>>>0?1:0),q=e.low=q+G,e.high=p+F+(G>>>0>q>>>0?1:0),s=f.low=s+I,f.high=r+H+(I>>>0>s>>>0?1:0),u=g.low=u+K,g.high=t+J+(K>>>0>u>>>0?1:0),w=h.low=w+M,h.high=v+L+(M>>>0>w>>>0?1:0),y=i.low=y+O,i.high=x+N+(O>>>0>y>>>0?1:0),A=l.low=A+Q,l.high=z+P+(Q>>>0>A>>>0?1:0),C=m.low=C+S,m.high=B+R+(S>>>0>C>>>0?1:0)},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32,b[(d+128>>>10<<5)+30]=Math.floor(c/4294967296),b[(d+128>>>10<<5)+31]=c,a.sigBytes=4*b.length,this._process();var e=this._hash.toX32();return e},clone:function(){var a=e.clone.call(this);return a._hash=this._hash.clone(),a},blockSize:32});c.SHA512=e._createHelper(l),c.HmacSHA512=e._createHmacHelper(l)}(),a.SHA512})},{"./core":38,"./x64-core":69}],68:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a,b){var c=(this._lBlock>>>a^this._rBlock)&b;this._rBlock^=c,this._lBlock^=c<<a}function c(a,b){var c=(this._rBlock>>>a^this._lBlock)&b;this._lBlock^=c,this._rBlock^=c<<a}var d=a,e=d.lib,f=e.WordArray,g=e.BlockCipher,h=d.algo,i=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],j=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],k=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],l=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],m=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],n=h.DES=g.extend({_doReset:function(){for(var a=this._key,b=a.words,c=[],d=0;56>d;d++){var e=i[d]-1;c[d]=b[e>>>5]>>>31-e%32&1}for(var f=this._subKeys=[],g=0;16>g;g++){for(var h=f[g]=[],l=k[g],d=0;24>d;d++)h[d/6|0]|=c[(j[d]-1+l)%28]<<31-d%6,h[4+(d/6|0)]|=c[28+(j[d+24]-1+l)%28]<<31-d%6;h[0]=h[0]<<1|h[0]>>>31;for(var d=1;7>d;d++)h[d]=h[d]>>>4*(d-1)+3;h[7]=h[7]<<5|h[7]>>>27}for(var m=this._invSubKeys=[],d=0;16>d;d++)m[d]=f[15-d]},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._subKeys)},decryptBlock:function(a,b){this._doCryptBlock(a,b,this._invSubKeys)},_doCryptBlock:function(a,d,e){this._lBlock=a[d],this._rBlock=a[d+1],b.call(this,4,252645135),b.call(this,16,65535),c.call(this,2,858993459),c.call(this,8,16711935),b.call(this,1,1431655765);for(var f=0;16>f;f++){for(var g=e[f],h=this._lBlock,i=this._rBlock,j=0,k=0;8>k;k++)j|=l[k][((i^g[k])&m[k])>>>0];this._lBlock=i,this._rBlock=h^j}var n=this._lBlock;this._lBlock=this._rBlock,this._rBlock=n,b.call(this,1,1431655765),c.call(this,8,16711935),c.call(this,2,858993459),b.call(this,16,65535),b.call(this,4,252645135),a[d]=this._lBlock,a[d+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});d.DES=g._createHelper(n);var o=h.TripleDES=g.extend({_doReset:function(){var a=this._key,b=a.words;this._des1=n.createEncryptor(f.create(b.slice(0,2))),this._des2=n.createEncryptor(f.create(b.slice(2,4))),this._des3=n.createEncryptor(f.create(b.slice(4,6)))},encryptBlock:function(a,b){this._des1.encryptBlock(a,b),this._des2.decryptBlock(a,b),this._des3.encryptBlock(a,b)},decryptBlock:function(a,b){this._des3.decryptBlock(a,b),this._des2.encryptBlock(a,b),this._des1.decryptBlock(a,b)},keySize:6,ivSize:2,blockSize:2});d.TripleDES=g._createHelper(o)}(),a.TripleDES})},{"./cipher-core":37,"./core":38,"./enc-base64":39,"./evpkdf":41,"./md5":46}],69:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.Base,f=d.WordArray,g=c.x64={};g.Word=e.extend({init:function(a,b){this.high=a,this.low=b}}),g.WordArray=e.extend({init:function(a,c){a=this.words=a||[],c!=b?this.sigBytes=c:this.sigBytes=8*a.length},toX32:function(){for(var a=this.words,b=a.length,c=[],d=0;b>d;d++){var e=a[d];c.push(e.high),c.push(e.low)}return f.create(c,this.sigBytes)},clone:function(){for(var a=e.clone.call(this),b=a.words=this.words.slice(0),c=b.length,d=0;c>d;d++)b[d]=b[d].clone();return a}})}(),a})},{"./core":38}],70:[function(a,b,c){function d(){k=!1,h.length?j=h.concat(j):l=-1,j.length&&e()}function e(){if(!k){var a=setTimeout(d);k=!0;for(var b=j.length;b;){for(h=j,j=[];++l<b;)h&&h[l].run();l=-1,b=j.length}h=null,k=!1,clearTimeout(a)}}function f(a,b){this.fun=a,this.array=b}function g(){}var h,i=b.exports={},j=[],k=!1,l=-1;i.nextTick=function(a){var b=new Array(arguments.length-1);if(arguments.length>1)for(var c=1;c<arguments.length;c++)b[c-1]=arguments[c];j.push(new f(a,b)),1!==j.length||k||setTimeout(e,0)},f.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=g,i.addListener=g,i.once=g,i.off=g,i.removeListener=g,i.removeAllListeners=g,i.emit=g,i.binding=function(a){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(a){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},{}],71:[function(a,b,c){(function(a,d){!function(){var b,c,e,f;!function(){var a={},d={};b=function(b,c,d){a[b]={deps:c,callback:d}},f=e=c=function(b){function e(a){if("."!==a.charAt(0))return a;for(var c=a.split("/"),d=b.split("/").slice(0,-1),e=0,f=c.length;f>e;e++){var g=c[e];if(".."===g)d.pop();else{if("."===g)continue;d.push(g)}}return d.join("/")}if(f._eak_seen=a,d[b])return d[b];if(d[b]={},!a[b])throw new Error("Could not find module "+b);for(var g,h=a[b],i=h.deps,j=h.callback,k=[],l=0,m=i.length;m>l;l++)"exports"===i[l]?k.push(g={}):k.push(c(e(i[l])));var n=j.apply(this,k);return d[b]=g||n}}(),b("promise/all",["./utils","exports"],function(a,b){"use strict";function c(a){var b=this;if(!d(a))throw new TypeError("You must pass an array to all.");return new b(function(b,c){function d(a){return function(b){f(a,b)}}function f(a,c){h[a]=c,0===--i&&b(h)}var g,h=[],i=a.length;0===i&&b([]);for(var j=0;j<a.length;j++)g=a[j],g&&e(g.then)?g.then(d(j),c):f(j,g)})}var d=a.isArray,e=a.isFunction;b.all=c}),b("promise/asap",["exports"],function(b){"use strict";function c(){return function(){a.nextTick(g)}}function e(){var a=0,b=new k(g),c=document.createTextNode("");return b.observe(c,{characterData:!0}),function(){c.data=a=++a%2}}function f(){return function(){l.setTimeout(g,1)}}function g(){for(var a=0;a<m.length;a++){var b=m[a],c=b[0],d=b[1];c(d)}m=[]}function h(a,b){var c=m.push([a,b]);1===c&&i()}var i,j="undefined"!=typeof window?window:{},k=j.MutationObserver||j.WebKitMutationObserver,l="undefined"!=typeof d?d:void 0===this?window:this,m=[];i="undefined"!=typeof a&&"[object process]"==={}.toString.call(a)?c():k?e():f(),b.asap=h}),b("promise/config",["exports"],function(a){"use strict";function b(a,b){return 2!==arguments.length?c[a]:void(c[a]=b)}var c={instrument:!1};a.config=c,a.configure=b}),b("promise/polyfill",["./promise","./utils","exports"],function(a,b,c){"use strict";function e(){var a;a="undefined"!=typeof d?d:"undefined"!=typeof window&&window.document?window:self;var b="Promise"in a&&"resolve"in a.Promise&&"reject"in a.Promise&&"all"in a.Promise&&"race"in a.Promise&&function(){var b;return new a.Promise(function(a){b=a}),g(b)}();b||(a.Promise=f)}var f=a.Promise,g=b.isFunction;c.polyfill=e}),b("promise/promise",["./config","./utils","./all","./race","./resolve","./reject","./asap","exports"],function(a,b,c,d,e,f,g,h){"use strict";function i(a){if(!v(a))throw new TypeError("You must pass a resolver function as the first argument to the promise constructor");if(!(this instanceof i))throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");this._subscribers=[],j(a,this)}function j(a,b){function c(a){o(b,a)}function d(a){q(b,a)}try{a(c,d)}catch(e){d(e)}}function k(a,b,c,d){var e,f,g,h,i=v(c);if(i)try{e=c(d),g=!0}catch(j){h=!0,f=j}else e=d,g=!0;n(b,e)||(i&&g?o(b,e):h?q(b,f):a===D?o(b,e):a===E&&q(b,e))}function l(a,b,c,d){var e=a._subscribers,f=e.length;e[f]=b,e[f+D]=c,e[f+E]=d}function m(a,b){for(var c,d,e=a._subscribers,f=a._detail,g=0;g<e.length;g+=3)c=e[g],d=e[g+b],k(b,c,d,f);a._subscribers=null}function n(a,b){var c,d=null;try{if(a===b)throw new TypeError("A promises callback cannot return that same promise.");if(u(b)&&(d=b.then,v(d)))return d.call(b,function(d){return c?!0:(c=!0,void(b!==d?o(a,d):p(a,d)))},function(b){return c?!0:(c=!0,void q(a,b))}),!0}catch(e){return c?!0:(q(a,e),!0)}return!1}function o(a,b){a===b?p(a,b):n(a,b)||p(a,b)}function p(a,b){a._state===B&&(a._state=C,a._detail=b,t.async(r,a))}function q(a,b){a._state===B&&(a._state=C,a._detail=b,t.async(s,a))}function r(a){m(a,a._state=D)}function s(a){m(a,a._state=E)}var t=a.config,u=(a.configure,b.objectOrFunction),v=b.isFunction,w=(b.now,c.all),x=d.race,y=e.resolve,z=f.reject,A=g.asap;t.async=A;var B=void 0,C=0,D=1,E=2;i.prototype={constructor:i,_state:void 0,_detail:void 0,_subscribers:void 0,then:function(a,b){var c=this,d=new this.constructor(function(){});if(this._state){var e=arguments;t.async(function(){k(c._state,d,e[c._state-1],c._detail)})}else l(this,d,a,b);return d},"catch":function(a){return this.then(null,a)}},i.all=w,i.race=x,i.resolve=y,i.reject=z,h.Promise=i}),b("promise/race",["./utils","exports"],function(a,b){"use strict";function c(a){var b=this;if(!d(a))throw new TypeError("You must pass an array to race.");return new b(function(b,c){for(var d,e=0;e<a.length;e++)d=a[e],d&&"function"==typeof d.then?d.then(b,c):b(d)})}var d=a.isArray;b.race=c}),b("promise/reject",["exports"],function(a){"use strict";function b(a){var b=this;return new b(function(b,c){c(a)})}a.reject=b}),b("promise/resolve",["exports"],function(a){"use strict";function b(a){if(a&&"object"==typeof a&&a.constructor===this)return a;var b=this;return new b(function(b){b(a)})}a.resolve=b}),b("promise/utils",["exports"],function(a){"use strict";function b(a){return c(a)||"object"==typeof a&&null!==a}function c(a){return"function"==typeof a}function d(a){return"[object Array]"===Object.prototype.toString.call(a)}var e=Date.now||function(){return(new Date).getTime()};a.objectOrFunction=b,a.isFunction=c,a.isArray=d,a.now=e}),c("promise/polyfill").polyfill()}(),function(a,d){"object"==typeof c&&"object"==typeof b?b.exports=d():"function"==typeof define&&define.amd?define([],d):"object"==typeof c?c.localforage=d():a.localforage=d()}(this,function(){return function(a){function b(d){if(c[d])return c[d].exports;var e=c[d]={exports:{},id:d,loaded:!1};return a[d].call(e.exports,e,e.exports,b),e.loaded=!0,e.exports}var c={};return b.m=a,b.c=c,b.p="",b(0)}([function(a,b,c){"use strict";function d(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}b.__esModule=!0,function(){function a(a,b){a[b]=function(){var c=arguments;return a.ready().then(function(){return a[b].apply(a,c)})}}function e(){for(var a=1;a<arguments.length;a++){var b=arguments[a];if(b)for(var c in b)b.hasOwnProperty(c)&&(m(b[c])?arguments[0][c]=b[c].slice():arguments[0][c]=b[c])}return arguments[0]}function f(a){for(var b in h)if(h.hasOwnProperty(b)&&h[b]===a)return!0;return!1}var g={},h={INDEXEDDB:"asyncStorage",LOCALSTORAGE:"localStorageWrapper",WEBSQL:"webSQLStorage"},i=[h.INDEXEDDB,h.WEBSQL,h.LOCALSTORAGE],j=["clear","getItem","iterate","key","keys","length","removeItem","setItem"],k={description:"",driver:i.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1},l=function(a){var b=b||a.indexedDB||a.webkitIndexedDB||a.mozIndexedDB||a.OIndexedDB||a.msIndexedDB,c={};return c[h.WEBSQL]=!!a.openDatabase,c[h.INDEXEDDB]=!!function(){if("undefined"!=typeof a.openDatabase&&a.navigator&&a.navigator.userAgent&&/Safari/.test(a.navigator.userAgent)&&!/Chrome/.test(a.navigator.userAgent))return!1;try{return b&&"function"==typeof b.open&&"undefined"!=typeof a.IDBKeyRange}catch(c){return!1}}(),c[h.LOCALSTORAGE]=!!function(){try{return a.localStorage&&"setItem"in a.localStorage&&a.localStorage.setItem}catch(b){return!1}}(),c}(this),m=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},n=function(){function b(a){d(this,b),this.INDEXEDDB=h.INDEXEDDB,this.LOCALSTORAGE=h.LOCALSTORAGE,this.WEBSQL=h.WEBSQL,this._defaultConfig=e({},k),this._config=e({},this._defaultConfig,a),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver)}return b.prototype.config=function(a){if("object"==typeof a){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var b in a)"storeName"===b&&(a[b]=a[b].replace(/\W/g,"_")),this._config[b]=a[b];return"driver"in a&&a.driver&&this.setDriver(this._config.driver),!0}return"string"==typeof a?this._config[a]:this._config},b.prototype.defineDriver=function(a,b,c){var d=new Promise(function(b,c){try{var d=a._driver,e=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver"),h=new Error("Custom driver name already in use: "+a._driver);if(!a._driver)return void c(e);if(f(a._driver))return void c(h);for(var i=j.concat("_initStorage"),k=0;k<i.length;k++){var m=i[k];if(!m||!a[m]||"function"!=typeof a[m])return void c(e)}var n=Promise.resolve(!0);"_support"in a&&(n=a._support&&"function"==typeof a._support?a._support():Promise.resolve(!!a._support)),n.then(function(c){l[d]=c,g[d]=a,b()},c)}catch(o){c(o)}});return d.then(b,c),d},b.prototype.driver=function(){return this._driver||null},b.prototype.getDriver=function(a,b,d){var e=this,h=function(){if(f(a))switch(a){case e.INDEXEDDB:return new Promise(function(a,b){a(c(1))});case e.LOCALSTORAGE:return new Promise(function(a,b){a(c(2))});case e.WEBSQL:return new Promise(function(a,b){a(c(4))})}else if(g[a])return Promise.resolve(g[a]);return Promise.reject(new Error("Driver not found."))}();return h.then(b,d),h},b.prototype.getSerializer=function(a){var b=new Promise(function(a,b){a(c(3))});return a&&"function"==typeof a&&b.then(function(b){a(b)}),b},b.prototype.ready=function(a){var b=this,c=b._driverSet.then(function(){return null===b._ready&&(b._ready=b._initDriver()),b._ready});return c.then(a,a),c},b.prototype.setDriver=function(a,b,c){function d(){f._config.driver=f.driver()}function e(a){return function(){function b(){for(;c<a.length;){var e=a[c];return c++,f._dbInfo=null,f._ready=null,f.getDriver(e).then(function(a){return f._extend(a),d(),f._ready=f._initStorage(f._config),f._ready})["catch"](b)}d();var g=new Error("No available storage method found.");return f._driverSet=Promise.reject(g),f._driverSet}var c=0;return b()}}var f=this;m(a)||(a=[a]);var g=this._getSupportedDrivers(a),h=null!==this._driverSet?this._driverSet["catch"](function(){return Promise.resolve()}):Promise.resolve();return this._driverSet=h.then(function(){var a=g[0];return f._dbInfo=null,f._ready=null,f.getDriver(a).then(function(a){f._driver=a._driver,d(),f._wrapLibraryMethodsWithReady(),f._initDriver=e(g)})})["catch"](function(){d();var a=new Error("No available storage method found.");return f._driverSet=Promise.reject(a),f._driverSet}),this._driverSet.then(b,c),this._driverSet},b.prototype.supports=function(a){return!!l[a]},b.prototype._extend=function(a){e(this,a)},b.prototype._getSupportedDrivers=function(a){for(var b=[],c=0,d=a.length;d>c;c++){var e=a[c];this.supports(e)&&b.push(e)}return b},b.prototype._wrapLibraryMethodsWithReady=function(){for(var b=0;b<j.length;b++)a(this,j[b])},b.prototype.createInstance=function(a){return new b(a)},b}(),o=new n;b["default"]=o}.call("undefined"!=typeof window?window:self),a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,function(){function a(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(c){if("TypeError"!==c.name)throw c;for(var d=x.BlobBuilder||x.MSBlobBuilder||x.MozBlobBuilder||x.WebKitBlobBuilder,e=new d,f=0;f<a.length;f+=1)e.append(a[f]);return e.getBlob(b.type)}}function c(a){for(var b=a.length,c=new ArrayBuffer(b),d=new Uint8Array(c),e=0;b>e;e++)d[e]=a.charCodeAt(e);return c}function d(a){return new Promise(function(b,c){var d=new XMLHttpRequest;d.open("GET",a),d.withCredentials=!0,d.responseType="arraybuffer",d.onreadystatechange=function(){return 4===d.readyState?200===d.status?b({response:d.response,type:d.getResponseHeader("Content-Type")}):void c({status:d.status,response:d.response}):void 0},d.send()})}function e(b){return new Promise(function(c,e){var f=a([""],{type:"image/png"}),g=b.transaction([B],"readwrite");g.objectStore(B).put(f,"key"),g.oncomplete=function(){var a=b.transaction([B],"readwrite"),f=a.objectStore(B).get("key");f.onerror=e,f.onsuccess=function(a){var b=a.target.result,e=URL.createObjectURL(b);d(e).then(function(a){c(!(!a||"image/png"!==a.type))},function(){c(!1)}).then(function(){URL.revokeObjectURL(e)})}}})["catch"](function(){return!1})}function f(a){return"boolean"==typeof z?Promise.resolve(z):e(a).then(function(a){return z=a})}function g(a){return new Promise(function(b,c){var d=new FileReader;d.onerror=c,d.onloadend=function(c){var d=btoa(c.target.result||"");b({__local_forage_encoded_blob:!0,data:d,type:a.type})},d.readAsBinaryString(a)})}function h(b){var d=c(atob(b.data));return a([d],{type:b.type})}function i(a){return a&&a.__local_forage_encoded_blob}function j(a){function b(){return Promise.resolve()}var c=this,d={db:null};if(a)for(var e in a)d[e]=a[e];A||(A={});var f=A[d.name];f||(f={forages:[],db:null},A[d.name]=f),f.forages.push(this);for(var g=[],h=0;h<f.forages.length;h++){var i=f.forages[h];i!==this&&g.push(i.ready()["catch"](b))}var j=f.forages.slice(0);return Promise.all(g).then(function(){return d.db=f.db,k(d)}).then(function(a){return d.db=a,n(d,c._defaultConfig.version)?l(d):a}).then(function(a){d.db=f.db=a,c._dbInfo=d;for(var b in j){var e=j[b];e!==c&&(e._dbInfo.db=d.db,e._dbInfo.version=d.version)}})}function k(a){return m(a,!1)}function l(a){return m(a,!0)}function m(a,b){return new Promise(function(c,d){if(a.db){if(!b)return c(a.db);a.db.close()}var e=[a.name];b&&e.push(a.version);var f=y.open.apply(y,e);b&&(f.onupgradeneeded=function(b){var c=f.result;try{c.createObjectStore(a.storeName),b.oldVersion<=1&&c.createObjectStore(B)}catch(d){if("ConstraintError"!==d.name)throw d;x.console.warn('The database "'+a.name+'" has been upgraded from version '+b.oldVersion+" to version "+b.newVersion+', but the storage "'+a.storeName+'" already exists.')}}),f.onerror=function(){d(f.error)},f.onsuccess=function(){c(f.result)}})}function n(a,b){if(!a.db)return!0;var c=!a.db.objectStoreNames.contains(a.storeName),d=a.version<a.db.version,e=a.version>a.db.version;if(d&&(a.version!==b&&x.console.warn('The database "'+a.name+"\" can't be downgraded from version "+a.db.version+" to version "+a.version+"."),a.version=a.db.version),e||c){if(c){var f=a.db.version+1;f>a.version&&(a.version=f)}return!0}return!1}function o(a,b){var c=this;"string"!=typeof a&&(x.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.get(a);g.onsuccess=function(){var a=g.result;void 0===a&&(a=null),i(a)&&(a=h(a)),b(a)},g.onerror=function(){d(g.error)}})["catch"](d)});return w(d,b),d}function p(a,b){var c=this,d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.openCursor(),j=1;g.onsuccess=function(){var c=g.result;if(c){var d=c.value;i(d)&&(d=h(d));var e=a(d,c.key,j++);void 0!==e?b(e):c["continue"]()}else b()},g.onerror=function(){d(g.error)}})["catch"](d)});return w(d,b),d}function q(a,b,c){var d=this;"string"!=typeof a&&(x.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new Promise(function(c,e){var h;d.ready().then(function(){return h=d._dbInfo,f(h.db)}).then(function(a){return!a&&b instanceof Blob?g(b):b}).then(function(b){var d=h.db.transaction(h.storeName,"readwrite"),f=d.objectStore(h.storeName);null===b&&(b=void 0);var g=f.put(b,a);d.oncomplete=function(){void 0===b&&(b=null),c(b)},d.onabort=d.onerror=function(){var a=g.error?g.error:g.transaction.error;e(a)}})["catch"](e)});return w(e,c),e}function r(a,b){var c=this;"string"!=typeof a&&(x.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readwrite"),g=f.objectStore(e.storeName),h=g["delete"](a);f.oncomplete=function(){b()},f.onerror=function(){d(h.error)},f.onabort=function(){var a=h.error?h.error:h.transaction.error;d(a)}})["catch"](d)});return w(d,b),d}function s(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readwrite"),f=e.objectStore(d.storeName),g=f.clear();e.oncomplete=function(){a()},e.onabort=e.onerror=function(){var a=g.error?g.error:g.transaction.error;c(a)}})["catch"](c)});return w(c,a),c}function t(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.count();f.onsuccess=function(){a(f.result)},f.onerror=function(){c(f.error)}})["catch"](c)});return w(c,a),c}function u(a,b){var c=this,d=new Promise(function(b,d){return 0>a?void b(null):void c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=!1,h=f.openCursor();h.onsuccess=function(){var c=h.result;return c?void(0===a?b(c.key):g?b(c.key):(g=!0,c.advance(a))):void b(null)},h.onerror=function(){d(h.error)}})["catch"](d)});return w(d,b),d}function v(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.openCursor(),g=[];f.onsuccess=function(){var b=f.result;return b?(g.push(b.key),void b["continue"]()):void a(g)},f.onerror=function(){c(f.error)}})["catch"](c)});return w(c,a),c}function w(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var x=this,y=y||this.indexedDB||this.webkitIndexedDB||this.mozIndexedDB||this.OIndexedDB||this.msIndexedDB;if(y){var z,A,B="local-forage-detect-blob-support",C={_driver:"asyncStorage",_initStorage:j,iterate:p,getItem:o,setItem:q,removeItem:r,clear:s,length:t,key:u,keys:v};b["default"]=C}}.call("undefined"!=typeof window?window:self),a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0,function(){function a(a){var b=this,d={};if(a)for(var e in a)d[e]=a[e];return d.keyPrefix=d.name+"/",d.storeName!==b._defaultConfig.storeName&&(d.keyPrefix+=d.storeName+"/"),b._dbInfo=d,new Promise(function(a,b){a(c(3))}).then(function(a){return d.serializer=a,Promise.resolve()})}function d(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo.keyPrefix,c=n.length-1;c>=0;c--){var d=n.key(c);0===d.indexOf(a)&&n.removeItem(d)}});return l(c,a),c}function e(a,b){var c=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo,d=n.getItem(b.keyPrefix+a);return d&&(d=b.serializer.deserialize(d)),d});return l(d,b),d}function f(a,b){var c=this,d=c.ready().then(function(){for(var b=c._dbInfo,d=b.keyPrefix,e=d.length,f=n.length,g=1,h=0;f>h;h++){var i=n.key(h);if(0===i.indexOf(d)){var j=n.getItem(i);if(j&&(j=b.serializer.deserialize(j)),j=a(j,i.substring(e),g++),void 0!==j)return j}}});return l(d,b),d}function g(a,b){var c=this,d=c.ready().then(function(){var b,d=c._dbInfo;try{b=n.key(a)}catch(e){b=null}return b&&(b=b.substring(d.keyPrefix.length)),b});return l(d,b),d}function h(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo,c=n.length,d=[],e=0;c>e;e++)0===n.key(e).indexOf(a.keyPrefix)&&d.push(n.key(e).substring(a.keyPrefix.length));return d});return l(c,a),c}function i(a){var b=this,c=b.keys().then(function(a){return a.length});return l(c,a),c}function j(a,b){var c=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){ var b=c._dbInfo;n.removeItem(b.keyPrefix+a)});return l(d,b),d}function k(a,b,c){var d=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=d.ready().then(function(){void 0===b&&(b=null);var c=b;return new Promise(function(e,f){var g=d._dbInfo;g.serializer.serialize(b,function(b,d){if(d)f(d);else try{n.setItem(g.keyPrefix+a,b),e(c)}catch(h){("QuotaExceededError"===h.name||"NS_ERROR_DOM_QUOTA_REACHED"===h.name)&&f(h),f(h)}})})});return l(e,c),e}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m=this,n=null;try{if(!(this.localStorage&&"setItem"in this.localStorage))return;n=this.localStorage}catch(o){return}var p={_driver:"localStorageWrapper",_initStorage:a,iterate:f,getItem:e,setItem:k,removeItem:j,clear:d,length:i,key:g,keys:h};b["default"]=p}.call("undefined"!=typeof window?window:self),a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,function(){function a(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(c){if("TypeError"!==c.name)throw c;for(var d=x.BlobBuilder||x.MSBlobBuilder||x.MozBlobBuilder||x.WebKitBlobBuilder,e=new d,f=0;f<a.length;f+=1)e.append(a[f]);return e.getBlob(b.type)}}function c(a,b){var c="";if(a&&(c=a.toString()),a&&("[object ArrayBuffer]"===a.toString()||a.buffer&&"[object ArrayBuffer]"===a.buffer.toString())){var d,e=j;a instanceof ArrayBuffer?(d=a,e+=l):(d=a.buffer,"[object Int8Array]"===c?e+=n:"[object Uint8Array]"===c?e+=o:"[object Uint8ClampedArray]"===c?e+=p:"[object Int16Array]"===c?e+=q:"[object Uint16Array]"===c?e+=s:"[object Int32Array]"===c?e+=r:"[object Uint32Array]"===c?e+=t:"[object Float32Array]"===c?e+=u:"[object Float64Array]"===c?e+=v:b(new Error("Failed to get type for BinaryArray"))),b(e+f(d))}else if("[object Blob]"===c){var g=new FileReader;g.onload=function(){var c=h+a.type+"~"+f(this.result);b(j+m+c)},g.readAsArrayBuffer(a)}else try{b(JSON.stringify(a))}catch(i){console.error("Couldn't convert value into a JSON string: ",a),b(null,i)}}function d(b){if(b.substring(0,k)!==j)return JSON.parse(b);var c,d=b.substring(w),f=b.substring(k,w);if(f===m&&i.test(d)){var g=d.match(i);c=g[1],d=d.substring(g[0].length)}var h=e(d);switch(f){case l:return h;case m:return a([h],{type:c});case n:return new Int8Array(h);case o:return new Uint8Array(h);case p:return new Uint8ClampedArray(h);case q:return new Int16Array(h);case s:return new Uint16Array(h);case r:return new Int32Array(h);case t:return new Uint32Array(h);case u:return new Float32Array(h);case v:return new Float64Array(h);default:throw new Error("Unkown type: "+f)}}function e(a){var b,c,d,e,f,h=.75*a.length,i=a.length,j=0;"="===a[a.length-1]&&(h--,"="===a[a.length-2]&&h--);var k=new ArrayBuffer(h),l=new Uint8Array(k);for(b=0;i>b;b+=4)c=g.indexOf(a[b]),d=g.indexOf(a[b+1]),e=g.indexOf(a[b+2]),f=g.indexOf(a[b+3]),l[j++]=c<<2|d>>4,l[j++]=(15&d)<<4|e>>2,l[j++]=(3&e)<<6|63&f;return k}function f(a){var b,c=new Uint8Array(a),d="";for(b=0;b<c.length;b+=3)d+=g[c[b]>>2],d+=g[(3&c[b])<<4|c[b+1]>>4],d+=g[(15&c[b+1])<<2|c[b+2]>>6],d+=g[63&c[b+2]];return c.length%3===2?d=d.substring(0,d.length-1)+"=":c.length%3===1&&(d=d.substring(0,d.length-2)+"=="),d}var g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",h="~~local_forage_type~",i=/^~~local_forage_type~([^~]+)~/,j="__lfsc__:",k=j.length,l="arbf",m="blob",n="si08",o="ui08",p="uic8",q="si16",r="si32",s="ur16",t="ui32",u="fl32",v="fl64",w=k+l.length,x=this,y={serialize:c,deserialize:d,stringToBuffer:e,bufferToString:f};b["default"]=y}.call("undefined"!=typeof window?window:self),a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0,function(){function a(a){var b=this,d={db:null};if(a)for(var e in a)d[e]="string"!=typeof a[e]?a[e].toString():a[e];var f=new Promise(function(c,e){try{d.db=n(d.name,String(d.version),d.description,d.size)}catch(f){return b.setDriver(b.LOCALSTORAGE).then(function(){return b._initStorage(a)}).then(c)["catch"](e)}d.db.transaction(function(a){a.executeSql("CREATE TABLE IF NOT EXISTS "+d.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){b._dbInfo=d,c()},function(a,b){e(b)})})});return new Promise(function(a,b){a(c(3))}).then(function(a){return d.serializer=a,f})}function d(a,b){var c=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName+" WHERE key = ? LIMIT 1",[a],function(a,c){var d=c.rows.length?c.rows.item(0).value:null;d&&(d=e.serializer.deserialize(d)),b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function e(a,b){var c=this,d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName,[],function(c,d){for(var f=d.rows,g=f.length,h=0;g>h;h++){var i=f.item(h),j=i.value;if(j&&(j=e.serializer.deserialize(j)),j=a(j,i.key,h+1),void 0!==j)return void b(j)}b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function f(a,b,c){var d=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new Promise(function(c,e){d.ready().then(function(){void 0===b&&(b=null);var f=b,g=d._dbInfo;g.serializer.serialize(b,function(b,d){d?e(d):g.db.transaction(function(d){d.executeSql("INSERT OR REPLACE INTO "+g.storeName+" (key, value) VALUES (?, ?)",[a,b],function(){c(f)},function(a,b){e(b)})},function(a){a.code===a.QUOTA_ERR&&e(a)})})})["catch"](e)});return l(e,c),e}function g(a,b){var c=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("DELETE FROM "+e.storeName+" WHERE key = ?",[a],function(){b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function h(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("DELETE FROM "+d.storeName,[],function(){a()},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function i(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT COUNT(key) as c FROM "+d.storeName,[],function(b,c){var d=c.rows.item(0).c;a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function j(a,b){var c=this,d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT key FROM "+e.storeName+" WHERE id = ? LIMIT 1",[a+1],function(a,c){var d=c.rows.length?c.rows.item(0).key:null;b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function k(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT key FROM "+d.storeName,[],function(b,c){for(var d=[],e=0;e<c.rows.length;e++)d.push(c.rows.item(e).key);a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m=this,n=this.openDatabase;if(n){var o={_driver:"webSQLStorage",_initStorage:a,iterate:e,getItem:d,setItem:f,removeItem:g,clear:h,length:i,key:j,keys:k};b["default"]=o}}.call("undefined"!=typeof window?window:self),a.exports=b["default"]}])})}).call(this,a("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:70}],72:[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":73,"./lib/inflate":74,"./lib/utils/common":75,"./lib/zlib/constants":78}],73:[function(a,b,c){"use strict";function d(a,b){var c=new u(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function e(a,b){return b=b||{},b.raw=!0,d(a,b)}function f(a,b){return b=b||{},b.gzip=!0,d(a,b)}var g=a("./zlib/deflate.js"),h=a("./utils/common"),i=a("./utils/strings"),j=a("./zlib/messages"),k=a("./zlib/zstream"),l=Object.prototype.toString,m=0,n=4,o=0,p=1,q=2,r=-1,s=0,t=8,u=function(a){this.options=h.assign({level:r,method:t,chunkSize:16384,windowBits:15,memLevel:8,strategy:s,to:""},a||{});var b=this.options;b.raw&&b.windowBits>0?b.windowBits=-b.windowBits:b.gzip&&b.windowBits>0&&b.windowBits<16&&(b.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new k,this.strm.avail_out=0;var c=g.deflateInit2(this.strm,b.level,b.method,b.windowBits,b.memLevel,b.strategy);if(c!==o)throw new Error(j[c]);b.header&&g.deflateSetHeader(this.strm,b.header)};u.prototype.push=function(a,b){var c,d,e=this.strm,f=this.options.chunkSize;if(this.ended)return!1;d=b===~~b?b:b===!0?n:m,"string"==typeof a?e.input=i.string2buf(a):"[object ArrayBuffer]"===l.call(a)?e.input=new Uint8Array(a):e.input=a,e.next_in=0,e.avail_in=e.input.length;do{if(0===e.avail_out&&(e.output=new h.Buf8(f),e.next_out=0,e.avail_out=f),c=g.deflate(e,d),c!==p&&c!==o)return this.onEnd(c),this.ended=!0,!1;(0===e.avail_out||0===e.avail_in&&(d===n||d===q))&&("string"===this.options.to?this.onData(i.buf2binstring(h.shrinkBuf(e.output,e.next_out))):this.onData(h.shrinkBuf(e.output,e.next_out)))}while((e.avail_in>0||0===e.avail_out)&&c!==p);return d===n?(c=g.deflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===o):d===q?(this.onEnd(o),e.avail_out=0,!0):!0},u.prototype.onData=function(a){this.chunks.push(a)},u.prototype.onEnd=function(a){a===o&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=h.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Deflate=u,c.deflate=d,c.deflateRaw=e,c.gzip=f},{"./utils/common":75,"./utils/strings":76,"./zlib/deflate.js":80,"./zlib/messages":85,"./zlib/zstream":87}],74:[function(a,b,c){"use strict";function d(a,b){var c=new n(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function e(a,b){return b=b||{},b.raw=!0,d(a,b)}var f=a("./zlib/inflate.js"),g=a("./utils/common"),h=a("./utils/strings"),i=a("./zlib/constants"),j=a("./zlib/messages"),k=a("./zlib/zstream"),l=a("./zlib/gzheader"),m=Object.prototype.toString,n=function(a){this.options=g.assign({chunkSize:16384,windowBits:0,to:""},a||{});var b=this.options;b.raw&&b.windowBits>=0&&b.windowBits<16&&(b.windowBits=-b.windowBits,0===b.windowBits&&(b.windowBits=-15)),!(b.windowBits>=0&&b.windowBits<16)||a&&a.windowBits||(b.windowBits+=32),b.windowBits>15&&b.windowBits<48&&0===(15&b.windowBits)&&(b.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new k,this.strm.avail_out=0;var c=f.inflateInit2(this.strm,b.windowBits);if(c!==i.Z_OK)throw new Error(j[c]);this.header=new l,f.inflateGetHeader(this.strm,this.header)};n.prototype.push=function(a,b){var c,d,e,j,k,l=this.strm,n=this.options.chunkSize,o=!1;if(this.ended)return!1;d=b===~~b?b:b===!0?i.Z_FINISH:i.Z_NO_FLUSH,"string"==typeof a?l.input=h.binstring2buf(a):"[object ArrayBuffer]"===m.call(a)?l.input=new Uint8Array(a):l.input=a,l.next_in=0,l.avail_in=l.input.length;do{if(0===l.avail_out&&(l.output=new g.Buf8(n),l.next_out=0,l.avail_out=n),c=f.inflate(l,i.Z_NO_FLUSH),c===i.Z_BUF_ERROR&&o===!0&&(c=i.Z_OK,o=!1),c!==i.Z_STREAM_END&&c!==i.Z_OK)return this.onEnd(c),this.ended=!0,!1;l.next_out&&(0===l.avail_out||c===i.Z_STREAM_END||0===l.avail_in&&(d===i.Z_FINISH||d===i.Z_SYNC_FLUSH))&&("string"===this.options.to?(e=h.utf8border(l.output,l.next_out),j=l.next_out-e,k=h.buf2string(l.output,e),l.next_out=j,l.avail_out=n-j,j&&g.arraySet(l.output,l.output,e,j,0),this.onData(k)):this.onData(g.shrinkBuf(l.output,l.next_out))),0===l.avail_in&&0===l.avail_out&&(o=!0)}while((l.avail_in>0||0===l.avail_out)&&c!==i.Z_STREAM_END);return c===i.Z_STREAM_END&&(d=i.Z_FINISH),d===i.Z_FINISH?(c=f.inflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===i.Z_OK):d===i.Z_SYNC_FLUSH?(this.onEnd(i.Z_OK),l.avail_out=0,!0):!0},n.prototype.onData=function(a){this.chunks.push(a)},n.prototype.onEnd=function(a){a===i.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=g.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Inflate=n,c.inflate=d,c.inflateRaw=e,c.ungzip=d},{"./utils/common":75,"./utils/strings":76,"./zlib/constants":78,"./zlib/gzheader":81,"./zlib/inflate.js":83,"./zlib/messages":85,"./zlib/zstream":87}],75:[function(a,b,c){"use strict";var d="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;c.assign=function(a){for(var b=Array.prototype.slice.call(arguments,1);b.length;){var c=b.shift();if(c){if("object"!=typeof c)throw new TypeError(c+"must be non-object");for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])}}return a},c.shrinkBuf=function(a,b){return a.length===b?a:a.subarray?a.subarray(0,b):(a.length=b,a)};var e={arraySet:function(a,b,c,d,e){if(b.subarray&&a.subarray)return void a.set(b.subarray(c,c+d),e);for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){var b,c,d,e,f,g;for(d=0,b=0,c=a.length;c>b;b++)d+=a[b].length;for(g=new Uint8Array(d),e=0,b=0,c=a.length;c>b;b++)f=a[b],g.set(f,e),e+=f.length;return g}},f={arraySet:function(a,b,c,d,e){for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){return[].concat.apply([],a)}};c.setTyped=function(a){a?(c.Buf8=Uint8Array,c.Buf16=Uint16Array,c.Buf32=Int32Array,c.assign(c,e)):(c.Buf8=Array,c.Buf16=Array,c.Buf32=Array,c.assign(c,f))},c.setTyped(d)},{}],76:[function(a,b,c){"use strict";function d(a,b){if(65537>b&&(a.subarray&&g||!a.subarray&&f))return String.fromCharCode.apply(null,e.shrinkBuf(a,b));for(var c="",d=0;b>d;d++)c+=String.fromCharCode(a[d]);return c}var e=a("./common"),f=!0,g=!0;try{String.fromCharCode.apply(null,[0])}catch(h){f=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(h){g=!1}for(var i=new e.Buf8(256),j=0;256>j;j++)i[j]=j>=252?6:j>=248?5:j>=240?4:j>=224?3:j>=192?2:1;i[254]=i[254]=1,c.string2buf=function(a){var b,c,d,f,g,h=a.length,i=0;for(f=0;h>f;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),i+=128>c?1:2048>c?2:65536>c?3:4;for(b=new e.Buf8(i),g=0,f=0;i>g;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),128>c?b[g++]=c:2048>c?(b[g++]=192|c>>>6,b[g++]=128|63&c):65536>c?(b[g++]=224|c>>>12,b[g++]=128|c>>>6&63,b[g++]=128|63&c):(b[g++]=240|c>>>18,b[g++]=128|c>>>12&63,b[g++]=128|c>>>6&63,b[g++]=128|63&c);return b},c.buf2binstring=function(a){return d(a,a.length)},c.binstring2buf=function(a){for(var b=new e.Buf8(a.length),c=0,d=b.length;d>c;c++)b[c]=a.charCodeAt(c);return b},c.buf2string=function(a,b){var c,e,f,g,h=b||a.length,j=new Array(2*h);for(e=0,c=0;h>c;)if(f=a[c++],128>f)j[e++]=f;else if(g=i[f],g>4)j[e++]=65533,c+=g-1;else{for(f&=2===g?31:3===g?15:7;g>1&&h>c;)f=f<<6|63&a[c++],g--;g>1?j[e++]=65533:65536>f?j[e++]=f:(f-=65536,j[e++]=55296|f>>10&1023,j[e++]=56320|1023&f)}return d(j,e)},c.utf8border=function(a,b){var c;for(b=b||a.length,b>a.length&&(b=a.length),c=b-1;c>=0&&128===(192&a[c]);)c--;return 0>c?b:0===c?b:c+i[a[c]]>b?c:b}},{"./common":75}],77:[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},{}],78:[function(a,b,c){b.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],79:[function(a,b,c){"use strict";function d(){for(var a,b=[],c=0;256>c;c++){a=c;for(var d=0;8>d;d++)a=1&a?3988292384^a>>>1:a>>>1;b[c]=a}return b}function e(a,b,c,d){var e=f,g=d+c;a=-1^a;for(var h=d;g>h;h++)a=a>>>8^e[255&(a^b[h])];return-1^a}var f=d();b.exports=e},{}],80:[function(a,b,c){"use strict";function d(a,b){return a.msg=G[b],b}function e(a){return(a<<1)-(a>4?9:0)}function f(a){for(var b=a.length;--b>=0;)a[b]=0}function g(a){var b=a.state,c=b.pending;c>a.avail_out&&(c=a.avail_out),0!==c&&(C.arraySet(a.output,b.pending_buf,b.pending_out,c,a.next_out),a.next_out+=c,b.pending_out+=c,a.total_out+=c,a.avail_out-=c,b.pending-=c,0===b.pending&&(b.pending_out=0))}function h(a,b){D._tr_flush_block(a,a.block_start>=0?a.block_start:-1,a.strstart-a.block_start,b),a.block_start=a.strstart,g(a.strm)}function i(a,b){a.pending_buf[a.pending++]=b}function j(a,b){a.pending_buf[a.pending++]=b>>>8&255,a.pending_buf[a.pending++]=255&b}function k(a,b,c,d){var e=a.avail_in;return e>d&&(e=d),0===e?0:(a.avail_in-=e,C.arraySet(b,a.input,a.next_in,e,c),1===a.state.wrap?a.adler=E(a.adler,b,e,c):2===a.state.wrap&&(a.adler=F(a.adler,b,e,c)),a.next_in+=e,a.total_in+=e,e)}function l(a,b){var c,d,e=a.max_chain_length,f=a.strstart,g=a.prev_length,h=a.nice_match,i=a.strstart>a.w_size-ja?a.strstart-(a.w_size-ja):0,j=a.window,k=a.w_mask,l=a.prev,m=a.strstart+ia,n=j[f+g-1],o=j[f+g];a.prev_length>=a.good_match&&(e>>=2),h>a.lookahead&&(h=a.lookahead);do if(c=b,j[c+g]===o&&j[c+g-1]===n&&j[c]===j[f]&&j[++c]===j[f+1]){f+=2,c++;do;while(j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&m>f);if(d=ia-(m-f),f=m-ia,d>g){if(a.match_start=b,g=d,d>=h)break;n=j[f+g-1],o=j[f+g]}}while((b=l[b&k])>i&&0!==--e);return g<=a.lookahead?g:a.lookahead}function m(a){var b,c,d,e,f,g=a.w_size;do{if(e=a.window_size-a.lookahead-a.strstart,a.strstart>=g+(g-ja)){C.arraySet(a.window,a.window,g,g,0),a.match_start-=g,a.strstart-=g,a.block_start-=g,c=a.hash_size,b=c;do d=a.head[--b],a.head[b]=d>=g?d-g:0;while(--c);c=g,b=c;do d=a.prev[--b],a.prev[b]=d>=g?d-g:0;while(--c);e+=g}if(0===a.strm.avail_in)break;if(c=k(a.strm,a.window,a.strstart+a.lookahead,e),a.lookahead+=c,a.lookahead+a.insert>=ha)for(f=a.strstart-a.insert,a.ins_h=a.window[f],a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+1])&a.hash_mask;a.insert&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+ha-1])&a.hash_mask,a.prev[f&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=f,f++,a.insert--,!(a.lookahead+a.insert<ha)););}while(a.lookahead<ja&&0!==a.strm.avail_in)}function n(a,b){var c=65535;for(c>a.pending_buf_size-5&&(c=a.pending_buf_size-5);;){if(a.lookahead<=1){if(m(a),0===a.lookahead&&b===H)return sa;if(0===a.lookahead)break}a.strstart+=a.lookahead,a.lookahead=0;var d=a.block_start+c;if((0===a.strstart||a.strstart>=d)&&(a.lookahead=a.strstart-d,a.strstart=d,h(a,!1),0===a.strm.avail_out))return sa;if(a.strstart-a.block_start>=a.w_size-ja&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.strstart>a.block_start&&(h(a,!1),0===a.strm.avail_out)?sa:sa}function o(a,b){for(var c,d;;){if(a.lookahead<ja){if(m(a),a.lookahead<ja&&b===H)return sa;if(0===a.lookahead)break}if(c=0,a.lookahead>=ha&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),0!==c&&a.strstart-c<=a.w_size-ja&&(a.match_length=l(a,c)),a.match_length>=ha)if(d=D._tr_tally(a,a.strstart-a.match_start,a.match_length-ha),a.lookahead-=a.match_length,a.match_length<=a.max_lazy_match&&a.lookahead>=ha){a.match_length--;do a.strstart++,a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart;while(0!==--a.match_length);a.strstart++}else a.strstart+=a.match_length,a.match_length=0,a.ins_h=a.window[a.strstart],a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+1])&a.hash_mask;else d=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++;if(d&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=a.strstart<ha-1?a.strstart:ha-1,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function p(a,b){for(var c,d,e;;){if(a.lookahead<ja){if(m(a),a.lookahead<ja&&b===H)return sa;if(0===a.lookahead)break}if(c=0,a.lookahead>=ha&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),a.prev_length=a.match_length,a.prev_match=a.match_start,a.match_length=ha-1,0!==c&&a.prev_length<a.max_lazy_match&&a.strstart-c<=a.w_size-ja&&(a.match_length=l(a,c),a.match_length<=5&&(a.strategy===S||a.match_length===ha&&a.strstart-a.match_start>4096)&&(a.match_length=ha-1)),a.prev_length>=ha&&a.match_length<=a.prev_length){e=a.strstart+a.lookahead-ha,d=D._tr_tally(a,a.strstart-1-a.prev_match,a.prev_length-ha),a.lookahead-=a.prev_length-1,a.prev_length-=2;do++a.strstart<=e&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart);while(0!==--a.prev_length);if(a.match_available=0,a.match_length=ha-1,a.strstart++,d&&(h(a,!1),0===a.strm.avail_out))return sa}else if(a.match_available){if(d=D._tr_tally(a,0,a.window[a.strstart-1]),d&&h(a,!1),a.strstart++,a.lookahead--,0===a.strm.avail_out)return sa}else a.match_available=1,a.strstart++,a.lookahead--}return a.match_available&&(d=D._tr_tally(a,0,a.window[a.strstart-1]),a.match_available=0),a.insert=a.strstart<ha-1?a.strstart:ha-1,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function q(a,b){for(var c,d,e,f,g=a.window;;){if(a.lookahead<=ia){if(m(a),a.lookahead<=ia&&b===H)return sa;if(0===a.lookahead)break}if(a.match_length=0,a.lookahead>=ha&&a.strstart>0&&(e=a.strstart-1,d=g[e],d===g[++e]&&d===g[++e]&&d===g[++e])){f=a.strstart+ia;do;while(d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&f>e);a.match_length=ia-(f-e),a.match_length>a.lookahead&&(a.match_length=a.lookahead)}if(a.match_length>=ha?(c=D._tr_tally(a,1,a.match_length-ha),a.lookahead-=a.match_length,a.strstart+=a.match_length,a.match_length=0):(c=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++),c&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function r(a,b){for(var c;;){if(0===a.lookahead&&(m(a),0===a.lookahead)){if(b===H)return sa;break}if(a.match_length=0,c=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++,c&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function s(a){a.window_size=2*a.w_size,f(a.head),a.max_lazy_match=B[a.level].max_lazy,a.good_match=B[a.level].good_length,a.nice_match=B[a.level].nice_length,a.max_chain_length=B[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=ha-1,a.match_available=0,a.ins_h=0}function t(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Y,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new C.Buf16(2*fa),this.dyn_dtree=new C.Buf16(2*(2*da+1)),this.bl_tree=new C.Buf16(2*(2*ea+1)),f(this.dyn_ltree),f(this.dyn_dtree),f(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new C.Buf16(ga+1),this.heap=new C.Buf16(2*ca+1),f(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new C.Buf16(2*ca+1),f(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function u(a){var b;return a&&a.state?(a.total_in=a.total_out=0,a.data_type=X,b=a.state,b.pending=0,b.pending_out=0,b.wrap<0&&(b.wrap=-b.wrap),b.status=b.wrap?la:qa,a.adler=2===b.wrap?0:1,b.last_flush=H,D._tr_init(b),M):d(a,O)}function v(a){var b=u(a);return b===M&&s(a.state),b}function w(a,b){return a&&a.state?2!==a.state.wrap?O:(a.state.gzhead=b,M):O}function x(a,b,c,e,f,g){if(!a)return O;var h=1;if(b===R&&(b=6),0>e?(h=0,e=-e):e>15&&(h=2,e-=16),1>f||f>Z||c!==Y||8>e||e>15||0>b||b>9||0>g||g>V)return d(a,O);8===e&&(e=9);var i=new t;return a.state=i,i.strm=a,i.wrap=h,i.gzhead=null,i.w_bits=e,i.w_size=1<<i.w_bits,i.w_mask=i.w_size-1,i.hash_bits=f+7,i.hash_size=1<<i.hash_bits,i.hash_mask=i.hash_size-1,i.hash_shift=~~((i.hash_bits+ha-1)/ha),i.window=new C.Buf8(2*i.w_size),i.head=new C.Buf16(i.hash_size),i.prev=new C.Buf16(i.w_size),i.lit_bufsize=1<<f+6,i.pending_buf_size=4*i.lit_bufsize,i.pending_buf=new C.Buf8(i.pending_buf_size),i.d_buf=i.lit_bufsize>>1,i.l_buf=3*i.lit_bufsize,i.level=b,i.strategy=g,i.method=c,v(a)}function y(a,b){return x(a,b,Y,$,_,W)}function z(a,b){var c,h,k,l;if(!a||!a.state||b>L||0>b)return a?d(a,O):O;if(h=a.state,!a.output||!a.input&&0!==a.avail_in||h.status===ra&&b!==K)return d(a,0===a.avail_out?Q:O);if(h.strm=a,c=h.last_flush,h.last_flush=b,h.status===la)if(2===h.wrap)a.adler=0,i(h,31),i(h,139),i(h,8),h.gzhead?(i(h,(h.gzhead.text?1:0)+(h.gzhead.hcrc?2:0)+(h.gzhead.extra?4:0)+(h.gzhead.name?8:0)+(h.gzhead.comment?16:0)),i(h,255&h.gzhead.time),i(h,h.gzhead.time>>8&255),i(h,h.gzhead.time>>16&255),i(h,h.gzhead.time>>24&255),i(h,9===h.level?2:h.strategy>=T||h.level<2?4:0),i(h,255&h.gzhead.os),h.gzhead.extra&&h.gzhead.extra.length&&(i(h,255&h.gzhead.extra.length),i(h,h.gzhead.extra.length>>8&255)),h.gzhead.hcrc&&(a.adler=F(a.adler,h.pending_buf,h.pending,0)),h.gzindex=0,h.status=ma):(i(h,0),i(h,0),i(h,0),i(h,0),i(h,0),i(h,9===h.level?2:h.strategy>=T||h.level<2?4:0),i(h,wa),h.status=qa);else{var m=Y+(h.w_bits-8<<4)<<8,n=-1;n=h.strategy>=T||h.level<2?0:h.level<6?1:6===h.level?2:3,m|=n<<6,0!==h.strstart&&(m|=ka),m+=31-m%31,h.status=qa,j(h,m),0!==h.strstart&&(j(h,a.adler>>>16),j(h,65535&a.adler)),a.adler=1}if(h.status===ma)if(h.gzhead.extra){for(k=h.pending;h.gzindex<(65535&h.gzhead.extra.length)&&(h.pending!==h.pending_buf_size||(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending!==h.pending_buf_size));)i(h,255&h.gzhead.extra[h.gzindex]),h.gzindex++;h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),h.gzindex===h.gzhead.extra.length&&(h.gzindex=0,h.status=na)}else h.status=na;if(h.status===na)if(h.gzhead.name){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.name.length?255&h.gzhead.name.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.gzindex=0,h.status=oa)}else h.status=oa;if(h.status===oa)if(h.gzhead.comment){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.comment.length?255&h.gzhead.comment.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.status=pa)}else h.status=pa;if(h.status===pa&&(h.gzhead.hcrc?(h.pending+2>h.pending_buf_size&&g(a),h.pending+2<=h.pending_buf_size&&(i(h,255&a.adler),i(h,a.adler>>8&255),a.adler=0,h.status=qa)):h.status=qa),0!==h.pending){if(g(a),0===a.avail_out)return h.last_flush=-1,M}else if(0===a.avail_in&&e(b)<=e(c)&&b!==K)return d(a,Q);if(h.status===ra&&0!==a.avail_in)return d(a,Q);if(0!==a.avail_in||0!==h.lookahead||b!==H&&h.status!==ra){var o=h.strategy===T?r(h,b):h.strategy===U?q(h,b):B[h.level].func(h,b);if((o===ua||o===va)&&(h.status=ra),o===sa||o===ua)return 0===a.avail_out&&(h.last_flush=-1),M;if(o===ta&&(b===I?D._tr_align(h):b!==L&&(D._tr_stored_block(h,0,0,!1),b===J&&(f(h.head),0===h.lookahead&&(h.strstart=0,h.block_start=0,h.insert=0))),g(a),0===a.avail_out))return h.last_flush=-1,M}return b!==K?M:h.wrap<=0?N:(2===h.wrap?(i(h,255&a.adler),i(h,a.adler>>8&255),i(h,a.adler>>16&255),i(h,a.adler>>24&255),i(h,255&a.total_in),i(h,a.total_in>>8&255),i(h,a.total_in>>16&255),i(h,a.total_in>>24&255)):(j(h,a.adler>>>16),j(h,65535&a.adler)),g(a),h.wrap>0&&(h.wrap=-h.wrap),0!==h.pending?M:N)}function A(a){var b;return a&&a.state?(b=a.state.status,b!==la&&b!==ma&&b!==na&&b!==oa&&b!==pa&&b!==qa&&b!==ra?d(a,O):(a.state=null,b===qa?d(a,P):M)):O}var B,C=a("../utils/common"),D=a("./trees"),E=a("./adler32"),F=a("./crc32"),G=a("./messages"),H=0,I=1,J=3,K=4,L=5,M=0,N=1,O=-2,P=-3,Q=-5,R=-1,S=1,T=2,U=3,V=4,W=0,X=2,Y=8,Z=9,$=15,_=8,aa=29,ba=256,ca=ba+1+aa,da=30,ea=19,fa=2*ca+1,ga=15,ha=3,ia=258,ja=ia+ha+1,ka=32,la=42,ma=69,na=73,oa=91,pa=103,qa=113,ra=666,sa=1,ta=2,ua=3,va=4,wa=3,xa=function(a,b,c,d,e){this.good_length=a,this.max_lazy=b,this.nice_length=c,this.max_chain=d,this.func=e};B=[new xa(0,0,0,0,n),new xa(4,4,8,4,o),new xa(4,5,16,8,o),new xa(4,6,32,32,o),new xa(4,4,16,16,p),new xa(8,16,32,32,p),new xa(8,16,128,128,p),new xa(8,32,128,256,p),new xa(32,128,258,1024,p),new xa(32,258,258,4096,p)],c.deflateInit=y,c.deflateInit2=x,c.deflateReset=v,c.deflateResetKeep=u,c.deflateSetHeader=w,c.deflate=z,c.deflateEnd=A,c.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":75,"./adler32":77,"./crc32":79,"./messages":85,"./trees":86}],81:[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},{}],82:[function(a,b,c){"use strict";var d=30,e=12;b.exports=function(a,b){var c,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C;c=a.state,f=a.next_in,B=a.input,g=f+(a.avail_in-5),h=a.next_out,C=a.output,i=h-(b-a.avail_out),j=h+(a.avail_out-257),k=c.dmax,l=c.wsize,m=c.whave,n=c.wnext,o=c.window,p=c.hold,q=c.bits,r=c.lencode,s=c.distcode,t=(1<<c.lenbits)-1,u=(1<<c.distbits)-1;a:do{15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=r[p&t];b:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,0===w)C[h++]=65535&v;else{if(!(16&w)){if(0===(64&w)){v=r[(65535&v)+(p&(1<<w)-1)];continue b}if(32&w){c.mode=e;break a}a.msg="invalid literal/length code",c.mode=d;break a}x=65535&v,w&=15,w&&(w>q&&(p+=B[f++]<<q,q+=8),x+=p&(1<<w)-1,p>>>=w,q-=w),15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=s[p&u];c:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,!(16&w)){if(0===(64&w)){v=s[(65535&v)+(p&(1<<w)-1)];continue c}a.msg="invalid distance code",c.mode=d;break a}if(y=65535&v,w&=15,w>q&&(p+=B[f++]<<q,q+=8,w>q&&(p+=B[f++]<<q,q+=8)),y+=p&(1<<w)-1,y>k){a.msg="invalid distance too far back",c.mode=d;break a}if(p>>>=w,q-=w,w=h-i,y>w){if(w=y-w,w>m&&c.sane){a.msg="invalid distance too far back",c.mode=d;break a}if(z=0,A=o,0===n){if(z+=l-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}else if(w>n){if(z+=l+n-w,w-=n,x>w){x-=w;do C[h++]=o[z++];while(--w);if(z=0,x>n){w=n,x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}}else if(z+=n-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}for(;x>2;)C[h++]=A[z++],C[h++]=A[z++],C[h++]=A[z++],x-=3;x&&(C[h++]=A[z++],x>1&&(C[h++]=A[z++]))}else{z=h-y;do C[h++]=C[z++],C[h++]=C[z++],C[h++]=C[z++],x-=3;while(x>2);x&&(C[h++]=C[z++],x>1&&(C[h++]=C[z++]))}break}}break}}while(g>f&&j>h);x=q>>3,f-=x,q-=x<<3,p&=(1<<q)-1,a.next_in=f,a.next_out=h,a.avail_in=g>f?5+(g-f):5-(f-g),a.avail_out=j>h?257+(j-h):257-(h-j),c.hold=p,c.bits=q}},{}],83:[function(a,b,c){"use strict";function d(a){return(a>>>24&255)+(a>>>8&65280)+((65280&a)<<8)+((255&a)<<24)}function e(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0, this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new r.Buf16(320),this.work=new r.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(a){var b;return a&&a.state?(b=a.state,a.total_in=a.total_out=b.total=0,a.msg="",b.wrap&&(a.adler=1&b.wrap),b.mode=K,b.last=0,b.havedict=0,b.dmax=32768,b.head=null,b.hold=0,b.bits=0,b.lencode=b.lendyn=new r.Buf32(oa),b.distcode=b.distdyn=new r.Buf32(pa),b.sane=1,b.back=-1,C):F}function g(a){var b;return a&&a.state?(b=a.state,b.wsize=0,b.whave=0,b.wnext=0,f(a)):F}function h(a,b){var c,d;return a&&a.state?(d=a.state,0>b?(c=0,b=-b):(c=(b>>4)+1,48>b&&(b&=15)),b&&(8>b||b>15)?F:(null!==d.window&&d.wbits!==b&&(d.window=null),d.wrap=c,d.wbits=b,g(a))):F}function i(a,b){var c,d;return a?(d=new e,a.state=d,d.window=null,c=h(a,b),c!==C&&(a.state=null),c):F}function j(a){return i(a,ra)}function k(a){if(sa){var b;for(p=new r.Buf32(512),q=new r.Buf32(32),b=0;144>b;)a.lens[b++]=8;for(;256>b;)a.lens[b++]=9;for(;280>b;)a.lens[b++]=7;for(;288>b;)a.lens[b++]=8;for(v(x,a.lens,0,288,p,0,a.work,{bits:9}),b=0;32>b;)a.lens[b++]=5;v(y,a.lens,0,32,q,0,a.work,{bits:5}),sa=!1}a.lencode=p,a.lenbits=9,a.distcode=q,a.distbits=5}function l(a,b,c,d){var e,f=a.state;return null===f.window&&(f.wsize=1<<f.wbits,f.wnext=0,f.whave=0,f.window=new r.Buf8(f.wsize)),d>=f.wsize?(r.arraySet(f.window,b,c-f.wsize,f.wsize,0),f.wnext=0,f.whave=f.wsize):(e=f.wsize-f.wnext,e>d&&(e=d),r.arraySet(f.window,b,c-d,e,f.wnext),d-=e,d?(r.arraySet(f.window,b,c-d,d,0),f.wnext=d,f.whave=f.wsize):(f.wnext+=e,f.wnext===f.wsize&&(f.wnext=0),f.whave<f.wsize&&(f.whave+=e))),0}function m(a,b){var c,e,f,g,h,i,j,m,n,o,p,q,oa,pa,qa,ra,sa,ta,ua,va,wa,xa,ya,za,Aa=0,Ba=new r.Buf8(4),Ca=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!a||!a.state||!a.output||!a.input&&0!==a.avail_in)return F;c=a.state,c.mode===V&&(c.mode=W),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,o=i,p=j,xa=C;a:for(;;)switch(c.mode){case K:if(0===c.wrap){c.mode=W;break}for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(2&c.wrap&&35615===m){c.check=0,Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0),m=0,n=0,c.mode=L;break}if(c.flags=0,c.head&&(c.head.done=!1),!(1&c.wrap)||(((255&m)<<8)+(m>>8))%31){a.msg="incorrect header check",c.mode=la;break}if((15&m)!==J){a.msg="unknown compression method",c.mode=la;break}if(m>>>=4,n-=4,wa=(15&m)+8,0===c.wbits)c.wbits=wa;else if(wa>c.wbits){a.msg="invalid window size",c.mode=la;break}c.dmax=1<<wa,a.adler=c.check=1,c.mode=512&m?T:V,m=0,n=0;break;case L:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.flags=m,(255&c.flags)!==J){a.msg="unknown compression method",c.mode=la;break}if(57344&c.flags){a.msg="unknown header flags set",c.mode=la;break}c.head&&(c.head.text=m>>8&1),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0,c.mode=M;case M:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.time=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,Ba[2]=m>>>16&255,Ba[3]=m>>>24&255,c.check=t(c.check,Ba,4,0)),m=0,n=0,c.mode=N;case N:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.xflags=255&m,c.head.os=m>>8),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0,c.mode=O;case O:if(1024&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length=m,c.head&&(c.head.extra_len=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0}else c.head&&(c.head.extra=null);c.mode=P;case P:if(1024&c.flags&&(q=c.length,q>i&&(q=i),q&&(c.head&&(wa=c.head.extra_len-c.length,c.head.extra||(c.head.extra=new Array(c.head.extra_len)),r.arraySet(c.head.extra,e,g,q,wa)),512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,c.length-=q),c.length))break a;c.length=0,c.mode=Q;case Q:if(2048&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.name+=String.fromCharCode(wa));while(wa&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.name=null);c.length=0,c.mode=R;case R:if(4096&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.comment+=String.fromCharCode(wa));while(wa&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.comment=null);c.mode=S;case S:if(512&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(65535&c.check)){a.msg="header crc mismatch",c.mode=la;break}m=0,n=0}c.head&&(c.head.hcrc=c.flags>>9&1,c.head.done=!0),a.adler=c.check=0,c.mode=V;break;case T:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}a.adler=c.check=d(m),m=0,n=0,c.mode=U;case U:if(0===c.havedict)return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,E;a.adler=c.check=1,c.mode=V;case V:if(b===A||b===B)break a;case W:if(c.last){m>>>=7&n,n-=7&n,c.mode=ia;break}for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}switch(c.last=1&m,m>>>=1,n-=1,3&m){case 0:c.mode=X;break;case 1:if(k(c),c.mode=ba,b===B){m>>>=2,n-=2;break a}break;case 2:c.mode=$;break;case 3:a.msg="invalid block type",c.mode=la}m>>>=2,n-=2;break;case X:for(m>>>=7&n,n-=7&n;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if((65535&m)!==(m>>>16^65535)){a.msg="invalid stored block lengths",c.mode=la;break}if(c.length=65535&m,m=0,n=0,c.mode=Y,b===B)break a;case Y:c.mode=Z;case Z:if(q=c.length){if(q>i&&(q=i),q>j&&(q=j),0===q)break a;r.arraySet(f,e,g,q,h),i-=q,g+=q,j-=q,h+=q,c.length-=q;break}c.mode=V;break;case $:for(;14>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.nlen=(31&m)+257,m>>>=5,n-=5,c.ndist=(31&m)+1,m>>>=5,n-=5,c.ncode=(15&m)+4,m>>>=4,n-=4,c.nlen>286||c.ndist>30){a.msg="too many length or distance symbols",c.mode=la;break}c.have=0,c.mode=_;case _:for(;c.have<c.ncode;){for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.lens[Ca[c.have++]]=7&m,m>>>=3,n-=3}for(;c.have<19;)c.lens[Ca[c.have++]]=0;if(c.lencode=c.lendyn,c.lenbits=7,ya={bits:c.lenbits},xa=v(w,c.lens,0,19,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid code lengths set",c.mode=la;break}c.have=0,c.mode=aa;case aa:for(;c.have<c.nlen+c.ndist;){for(;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(16>sa)m>>>=qa,n-=qa,c.lens[c.have++]=sa;else{if(16===sa){for(za=qa+2;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m>>>=qa,n-=qa,0===c.have){a.msg="invalid bit length repeat",c.mode=la;break}wa=c.lens[c.have-1],q=3+(3&m),m>>>=2,n-=2}else if(17===sa){for(za=qa+3;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=3+(7&m),m>>>=3,n-=3}else{for(za=qa+7;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=11+(127&m),m>>>=7,n-=7}if(c.have+q>c.nlen+c.ndist){a.msg="invalid bit length repeat",c.mode=la;break}for(;q--;)c.lens[c.have++]=wa}}if(c.mode===la)break;if(0===c.lens[256]){a.msg="invalid code -- missing end-of-block",c.mode=la;break}if(c.lenbits=9,ya={bits:c.lenbits},xa=v(x,c.lens,0,c.nlen,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid literal/lengths set",c.mode=la;break}if(c.distbits=6,c.distcode=c.distdyn,ya={bits:c.distbits},xa=v(y,c.lens,c.nlen,c.ndist,c.distcode,0,c.work,ya),c.distbits=ya.bits,xa){a.msg="invalid distances set",c.mode=la;break}if(c.mode=ba,b===B)break a;case ba:c.mode=ca;case ca:if(i>=6&&j>=258){a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,u(a,p),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,c.mode===V&&(c.back=-1);break}for(c.back=0;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(ra&&0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.lencode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=ta+qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,c.length=sa,0===ra){c.mode=ha;break}if(32&ra){c.back=-1,c.mode=V;break}if(64&ra){a.msg="invalid literal/length code",c.mode=la;break}c.extra=15&ra,c.mode=da;case da:if(c.extra){for(za=c.extra;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}c.was=c.length,c.mode=ea;case ea:for(;Aa=c.distcode[m&(1<<c.distbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.distcode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=ta+qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,64&ra){a.msg="invalid distance code",c.mode=la;break}c.offset=sa,c.extra=15&ra,c.mode=fa;case fa:if(c.extra){for(za=c.extra;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.offset+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}if(c.offset>c.dmax){a.msg="invalid distance too far back",c.mode=la;break}c.mode=ga;case ga:if(0===j)break a;if(q=p-j,c.offset>q){if(q=c.offset-q,q>c.whave&&c.sane){a.msg="invalid distance too far back",c.mode=la;break}q>c.wnext?(q-=c.wnext,oa=c.wsize-q):oa=c.wnext-q,q>c.length&&(q=c.length),pa=c.window}else pa=f,oa=h-c.offset,q=c.length;q>j&&(q=j),j-=q,c.length-=q;do f[h++]=pa[oa++];while(--q);0===c.length&&(c.mode=ca);break;case ha:if(0===j)break a;f[h++]=c.length,j--,c.mode=ca;break;case ia:if(c.wrap){for(;32>n;){if(0===i)break a;i--,m|=e[g++]<<n,n+=8}if(p-=j,a.total_out+=p,c.total+=p,p&&(a.adler=c.check=c.flags?t(c.check,f,p,h-p):s(c.check,f,p,h-p)),p=j,(c.flags?m:d(m))!==c.check){a.msg="incorrect data check",c.mode=la;break}m=0,n=0}c.mode=ja;case ja:if(c.wrap&&c.flags){for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(4294967295&c.total)){a.msg="incorrect length check",c.mode=la;break}m=0,n=0}c.mode=ka;case ka:xa=D;break a;case la:xa=G;break a;case ma:return H;case na:default:return F}return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,(c.wsize||p!==a.avail_out&&c.mode<la&&(c.mode<ia||b!==z))&&l(a,a.output,a.next_out,p-a.avail_out)?(c.mode=ma,H):(o-=a.avail_in,p-=a.avail_out,a.total_in+=o,a.total_out+=p,c.total+=p,c.wrap&&p&&(a.adler=c.check=c.flags?t(c.check,f,p,a.next_out-p):s(c.check,f,p,a.next_out-p)),a.data_type=c.bits+(c.last?64:0)+(c.mode===V?128:0)+(c.mode===ba||c.mode===Y?256:0),(0===o&&0===p||b===z)&&xa===C&&(xa=I),xa)}function n(a){if(!a||!a.state)return F;var b=a.state;return b.window&&(b.window=null),a.state=null,C}function o(a,b){var c;return a&&a.state?(c=a.state,0===(2&c.wrap)?F:(c.head=b,b.done=!1,C)):F}var p,q,r=a("../utils/common"),s=a("./adler32"),t=a("./crc32"),u=a("./inffast"),v=a("./inftrees"),w=0,x=1,y=2,z=4,A=5,B=6,C=0,D=1,E=2,F=-2,G=-3,H=-4,I=-5,J=8,K=1,L=2,M=3,N=4,O=5,P=6,Q=7,R=8,S=9,T=10,U=11,V=12,W=13,X=14,Y=15,Z=16,$=17,_=18,aa=19,ba=20,ca=21,da=22,ea=23,fa=24,ga=25,ha=26,ia=27,ja=28,ka=29,la=30,ma=31,na=32,oa=852,pa=592,qa=15,ra=qa,sa=!0;c.inflateReset=g,c.inflateReset2=h,c.inflateResetKeep=f,c.inflateInit=j,c.inflateInit2=i,c.inflate=m,c.inflateEnd=n,c.inflateGetHeader=o,c.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":75,"./adler32":77,"./crc32":79,"./inffast":82,"./inftrees":84}],84:[function(a,b,c){"use strict";var d=a("../utils/common"),e=15,f=852,g=592,h=0,i=1,j=2,k=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],l=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],m=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],n=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];b.exports=function(a,b,c,o,p,q,r,s){var t,u,v,w,x,y,z,A,B,C=s.bits,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=null,O=0,P=new d.Buf16(e+1),Q=new d.Buf16(e+1),R=null,S=0;for(D=0;e>=D;D++)P[D]=0;for(E=0;o>E;E++)P[b[c+E]]++;for(H=C,G=e;G>=1&&0===P[G];G--);if(H>G&&(H=G),0===G)return p[q++]=20971520,p[q++]=20971520,s.bits=1,0;for(F=1;G>F&&0===P[F];F++);for(F>H&&(H=F),K=1,D=1;e>=D;D++)if(K<<=1,K-=P[D],0>K)return-1;if(K>0&&(a===h||1!==G))return-1;for(Q[1]=0,D=1;e>D;D++)Q[D+1]=Q[D]+P[D];for(E=0;o>E;E++)0!==b[c+E]&&(r[Q[b[c+E]]++]=E);if(a===h?(N=R=r,y=19):a===i?(N=k,O-=257,R=l,S-=257,y=256):(N=m,R=n,y=-1),M=0,E=0,D=F,x=q,I=H,J=0,v=-1,L=1<<H,w=L-1,a===i&&L>f||a===j&&L>g)return 1;for(var T=0;;){T++,z=D-J,r[E]<y?(A=0,B=r[E]):r[E]>y?(A=R[S+r[E]],B=N[O+r[E]]):(A=96,B=0),t=1<<D-J,u=1<<I,F=u;do u-=t,p[x+(M>>J)+u]=z<<24|A<<16|B|0;while(0!==u);for(t=1<<D-1;M&t;)t>>=1;if(0!==t?(M&=t-1,M+=t):M=0,E++,0===--P[D]){if(D===G)break;D=b[c+r[E]]}if(D>H&&(M&w)!==v){for(0===J&&(J=H),x+=F,I=D-J,K=1<<I;G>I+J&&(K-=P[I+J],!(0>=K));)I++,K<<=1;if(L+=1<<I,a===i&&L>f||a===j&&L>g)return 1;v=M&w,p[v]=H<<24|I<<16|x-q|0}}return 0!==M&&(p[x+M]=D-J<<24|64<<16|0),s.bits=H,0}},{"../utils/common":75}],85:[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"}},{}],86:[function(a,b,c){"use strict";function d(a){for(var b=a.length;--b>=0;)a[b]=0}function e(a){return 256>a?ga[a]:ga[256+(a>>>7)]}function f(a,b){a.pending_buf[a.pending++]=255&b,a.pending_buf[a.pending++]=b>>>8&255}function g(a,b,c){a.bi_valid>V-c?(a.bi_buf|=b<<a.bi_valid&65535,f(a,a.bi_buf),a.bi_buf=b>>V-a.bi_valid,a.bi_valid+=c-V):(a.bi_buf|=b<<a.bi_valid&65535,a.bi_valid+=c)}function h(a,b,c){g(a,c[2*b],c[2*b+1])}function i(a,b){var c=0;do c|=1&a,a>>>=1,c<<=1;while(--b>0);return c>>>1}function j(a){16===a.bi_valid?(f(a,a.bi_buf),a.bi_buf=0,a.bi_valid=0):a.bi_valid>=8&&(a.pending_buf[a.pending++]=255&a.bi_buf,a.bi_buf>>=8,a.bi_valid-=8)}function k(a,b){var c,d,e,f,g,h,i=b.dyn_tree,j=b.max_code,k=b.stat_desc.static_tree,l=b.stat_desc.has_stree,m=b.stat_desc.extra_bits,n=b.stat_desc.extra_base,o=b.stat_desc.max_length,p=0;for(f=0;U>=f;f++)a.bl_count[f]=0;for(i[2*a.heap[a.heap_max]+1]=0,c=a.heap_max+1;T>c;c++)d=a.heap[c],f=i[2*i[2*d+1]+1]+1,f>o&&(f=o,p++),i[2*d+1]=f,d>j||(a.bl_count[f]++,g=0,d>=n&&(g=m[d-n]),h=i[2*d],a.opt_len+=h*(f+g),l&&(a.static_len+=h*(k[2*d+1]+g)));if(0!==p){do{for(f=o-1;0===a.bl_count[f];)f--;a.bl_count[f]--,a.bl_count[f+1]+=2,a.bl_count[o]--,p-=2}while(p>0);for(f=o;0!==f;f--)for(d=a.bl_count[f];0!==d;)e=a.heap[--c],e>j||(i[2*e+1]!==f&&(a.opt_len+=(f-i[2*e+1])*i[2*e],i[2*e+1]=f),d--)}}function l(a,b,c){var d,e,f=new Array(U+1),g=0;for(d=1;U>=d;d++)f[d]=g=g+c[d-1]<<1;for(e=0;b>=e;e++){var h=a[2*e+1];0!==h&&(a[2*e]=i(f[h]++,h))}}function m(){var a,b,c,d,e,f=new Array(U+1);for(c=0,d=0;O-1>d;d++)for(ia[d]=c,a=0;a<1<<_[d];a++)ha[c++]=d;for(ha[c-1]=d,e=0,d=0;16>d;d++)for(ja[d]=e,a=0;a<1<<aa[d];a++)ga[e++]=d;for(e>>=7;R>d;d++)for(ja[d]=e<<7,a=0;a<1<<aa[d]-7;a++)ga[256+e++]=d;for(b=0;U>=b;b++)f[b]=0;for(a=0;143>=a;)ea[2*a+1]=8,a++,f[8]++;for(;255>=a;)ea[2*a+1]=9,a++,f[9]++;for(;279>=a;)ea[2*a+1]=7,a++,f[7]++;for(;287>=a;)ea[2*a+1]=8,a++,f[8]++;for(l(ea,Q+1,f),a=0;R>a;a++)fa[2*a+1]=5,fa[2*a]=i(a,5);ka=new na(ea,_,P+1,Q,U),la=new na(fa,aa,0,R,U),ma=new na(new Array(0),ba,0,S,W)}function n(a){var b;for(b=0;Q>b;b++)a.dyn_ltree[2*b]=0;for(b=0;R>b;b++)a.dyn_dtree[2*b]=0;for(b=0;S>b;b++)a.bl_tree[2*b]=0;a.dyn_ltree[2*X]=1,a.opt_len=a.static_len=0,a.last_lit=a.matches=0}function o(a){a.bi_valid>8?f(a,a.bi_buf):a.bi_valid>0&&(a.pending_buf[a.pending++]=a.bi_buf),a.bi_buf=0,a.bi_valid=0}function p(a,b,c,d){o(a),d&&(f(a,c),f(a,~c)),E.arraySet(a.pending_buf,a.window,b,c,a.pending),a.pending+=c}function q(a,b,c,d){var e=2*b,f=2*c;return a[e]<a[f]||a[e]===a[f]&&d[b]<=d[c]}function r(a,b,c){for(var d=a.heap[c],e=c<<1;e<=a.heap_len&&(e<a.heap_len&&q(b,a.heap[e+1],a.heap[e],a.depth)&&e++,!q(b,d,a.heap[e],a.depth));)a.heap[c]=a.heap[e],c=e,e<<=1;a.heap[c]=d}function s(a,b,c){var d,f,i,j,k=0;if(0!==a.last_lit)do d=a.pending_buf[a.d_buf+2*k]<<8|a.pending_buf[a.d_buf+2*k+1],f=a.pending_buf[a.l_buf+k],k++,0===d?h(a,f,b):(i=ha[f],h(a,i+P+1,b),j=_[i],0!==j&&(f-=ia[i],g(a,f,j)),d--,i=e(d),h(a,i,c),j=aa[i],0!==j&&(d-=ja[i],g(a,d,j)));while(k<a.last_lit);h(a,X,b)}function t(a,b){var c,d,e,f=b.dyn_tree,g=b.stat_desc.static_tree,h=b.stat_desc.has_stree,i=b.stat_desc.elems,j=-1;for(a.heap_len=0,a.heap_max=T,c=0;i>c;c++)0!==f[2*c]?(a.heap[++a.heap_len]=j=c,a.depth[c]=0):f[2*c+1]=0;for(;a.heap_len<2;)e=a.heap[++a.heap_len]=2>j?++j:0,f[2*e]=1,a.depth[e]=0,a.opt_len--,h&&(a.static_len-=g[2*e+1]);for(b.max_code=j,c=a.heap_len>>1;c>=1;c--)r(a,f,c);e=i;do c=a.heap[1],a.heap[1]=a.heap[a.heap_len--],r(a,f,1),d=a.heap[1],a.heap[--a.heap_max]=c,a.heap[--a.heap_max]=d,f[2*e]=f[2*c]+f[2*d],a.depth[e]=(a.depth[c]>=a.depth[d]?a.depth[c]:a.depth[d])+1,f[2*c+1]=f[2*d+1]=e,a.heap[1]=e++,r(a,f,1);while(a.heap_len>=2);a.heap[--a.heap_max]=a.heap[1],k(a,b),l(f,j,a.bl_count)}function u(a,b,c){var d,e,f=-1,g=b[1],h=0,i=7,j=4;for(0===g&&(i=138,j=3),b[2*(c+1)+1]=65535,d=0;c>=d;d++)e=g,g=b[2*(d+1)+1],++h<i&&e===g||(j>h?a.bl_tree[2*e]+=h:0!==e?(e!==f&&a.bl_tree[2*e]++,a.bl_tree[2*Y]++):10>=h?a.bl_tree[2*Z]++:a.bl_tree[2*$]++,h=0,f=e,0===g?(i=138,j=3):e===g?(i=6,j=3):(i=7,j=4))}function v(a,b,c){var d,e,f=-1,i=b[1],j=0,k=7,l=4;for(0===i&&(k=138,l=3),d=0;c>=d;d++)if(e=i,i=b[2*(d+1)+1],!(++j<k&&e===i)){if(l>j){do h(a,e,a.bl_tree);while(0!==--j)}else 0!==e?(e!==f&&(h(a,e,a.bl_tree),j--),h(a,Y,a.bl_tree),g(a,j-3,2)):10>=j?(h(a,Z,a.bl_tree),g(a,j-3,3)):(h(a,$,a.bl_tree),g(a,j-11,7));j=0,f=e,0===i?(k=138,l=3):e===i?(k=6,l=3):(k=7,l=4)}}function w(a){var b;for(u(a,a.dyn_ltree,a.l_desc.max_code),u(a,a.dyn_dtree,a.d_desc.max_code),t(a,a.bl_desc),b=S-1;b>=3&&0===a.bl_tree[2*ca[b]+1];b--);return a.opt_len+=3*(b+1)+5+5+4,b}function x(a,b,c,d){var e;for(g(a,b-257,5),g(a,c-1,5),g(a,d-4,4),e=0;d>e;e++)g(a,a.bl_tree[2*ca[e]+1],3);v(a,a.dyn_ltree,b-1),v(a,a.dyn_dtree,c-1)}function y(a){var b,c=4093624447;for(b=0;31>=b;b++,c>>>=1)if(1&c&&0!==a.dyn_ltree[2*b])return G;if(0!==a.dyn_ltree[18]||0!==a.dyn_ltree[20]||0!==a.dyn_ltree[26])return H;for(b=32;P>b;b++)if(0!==a.dyn_ltree[2*b])return H;return G}function z(a){pa||(m(),pa=!0),a.l_desc=new oa(a.dyn_ltree,ka),a.d_desc=new oa(a.dyn_dtree,la),a.bl_desc=new oa(a.bl_tree,ma),a.bi_buf=0,a.bi_valid=0,n(a)}function A(a,b,c,d){g(a,(J<<1)+(d?1:0),3),p(a,b,c,!0)}function B(a){g(a,K<<1,3),h(a,X,ea),j(a)}function C(a,b,c,d){var e,f,h=0;a.level>0?(a.strm.data_type===I&&(a.strm.data_type=y(a)),t(a,a.l_desc),t(a,a.d_desc),h=w(a),e=a.opt_len+3+7>>>3,f=a.static_len+3+7>>>3,e>=f&&(e=f)):e=f=c+5,e>=c+4&&-1!==b?A(a,b,c,d):a.strategy===F||f===e?(g(a,(K<<1)+(d?1:0),3),s(a,ea,fa)):(g(a,(L<<1)+(d?1:0),3),x(a,a.l_desc.max_code+1,a.d_desc.max_code+1,h+1),s(a,a.dyn_ltree,a.dyn_dtree)),n(a),d&&o(a)}function D(a,b,c){return a.pending_buf[a.d_buf+2*a.last_lit]=b>>>8&255,a.pending_buf[a.d_buf+2*a.last_lit+1]=255&b,a.pending_buf[a.l_buf+a.last_lit]=255&c,a.last_lit++,0===b?a.dyn_ltree[2*c]++:(a.matches++,b--,a.dyn_ltree[2*(ha[c]+P+1)]++,a.dyn_dtree[2*e(b)]++),a.last_lit===a.lit_bufsize-1}var E=a("../utils/common"),F=4,G=0,H=1,I=2,J=0,K=1,L=2,M=3,N=258,O=29,P=256,Q=P+1+O,R=30,S=19,T=2*Q+1,U=15,V=16,W=7,X=256,Y=16,Z=17,$=18,_=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],aa=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],ba=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],ca=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],da=512,ea=new Array(2*(Q+2));d(ea);var fa=new Array(2*R);d(fa);var ga=new Array(da);d(ga);var ha=new Array(N-M+1);d(ha);var ia=new Array(O);d(ia);var ja=new Array(R);d(ja);var ka,la,ma,na=function(a,b,c,d,e){this.static_tree=a,this.extra_bits=b,this.extra_base=c,this.elems=d,this.max_length=e,this.has_stree=a&&a.length},oa=function(a,b){this.dyn_tree=a,this.max_code=0,this.stat_desc=b},pa=!1;c._tr_init=z,c._tr_stored_block=A,c._tr_flush_block=C,c._tr_tally=D,c._tr_align=B},{"../utils/common":75}],87:[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]);
app/jsx/assignments_2/teacher/components/Overrides/SubmissionTypes/OperatorType.js
djbender/canvas-lms
/* * Copyright (C) 2018 - 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 {string} from 'prop-types' import I18n from 'i18n!assignments_2' import {Flex, View} from '@instructure/ui-layout' import {Text} from '@instructure/ui-elements' export default class OperatorType extends React.Component { static propTypes = { value: string.isRequired } static defaultProps = { value: 'or' } render() { const display = this.props.value === 'or' ? I18n.t('Or') : I18n.t('And') return ( <View display="inline-block" width="100%"> <Flex margin="0 x-small 0 0" justifyItems="center"> <Flex.Item borderWidth="small" borderRadius="medium" padding="x-small x-small"> <Text>{display}</Text> </Flex.Item> </Flex> </View> ) } }
src/components/GithubButton/GithubButton.js
frankleng/react-redux-universal-hot-example
import React from 'react'; const GithubButton = (props) => { const {user, repo, type, width, height, count, large} = props; let src = `https://ghbtns.com/github-btn.html?user=${user}&repo=${repo}&type=${type}`; if (count) src += '&count=true'; if (large) src += '&size=large'; return ( <iframe src={src} frameBorder="0" allowTransparency="true" scrolling="0" width={width} height={height} style={{border: 'none', width: width, height: height}}></iframe> ); }; GithubButton.propTypes = { user: React.PropTypes.string.isRequired, repo: React.PropTypes.string.isRequired, type: React.PropTypes.oneOf(['star', 'watch', 'fork', 'follow']).isRequired, width: React.PropTypes.number.isRequired, height: React.PropTypes.number.isRequired, count: React.PropTypes.bool, large: React.PropTypes.bool }; export default GithubButton;
ajax/libs/yui/3.10.1/simpleyui/simpleyui.js
paleozogt/cdnjs
/** The YUI module contains the components required for building the YUI seed file. This includes the script loading mechanism, a simple queue, and the core utilities for the library. @module yui @main yui @submodule yui-base **/ /*jshint eqeqeq: false*/ if (typeof YUI != 'undefined') { YUI._YUI = YUI; } /** The YUI global namespace object. This is the constructor for all YUI instances. This is a self-instantiable factory function, meaning you don't need to precede it with the `new` operator. You can invoke it directly like this: YUI().use('*', function (Y) { // Y is a new YUI instance. }); But it also works like this: var Y = YUI(); The `YUI` constructor accepts an optional config object, like this: YUI({ debug: true, combine: false }).use('node', function (Y) { // Y.Node is ready to use. }); See the API docs for the <a href="config.html">Config</a> class for the complete list of supported configuration properties accepted by the YUI constuctor. If a global `YUI` object is already defined, the existing YUI object will not be overwritten, to ensure that defined namespaces are preserved. Each YUI instance has full custom event support, but only if the event system is available. @class YUI @uses EventTarget @constructor @global @param {Object} [config]* Zero or more optional configuration objects. Config values are stored in the `Y.config` property. See the <a href="config.html">Config</a> docs for the list of supported properties. **/ /*global YUI*/ /*global YUI_config*/ var YUI = function() { var i = 0, Y = this, args = arguments, l = args.length, instanceOf = function(o, type) { return (o && o.hasOwnProperty && (o instanceof type)); }, gconf = (typeof YUI_config !== 'undefined') && YUI_config; if (!(instanceOf(Y, YUI))) { Y = new YUI(); } else { // set up the core environment Y._init(); /** Master configuration that might span multiple contexts in a non- browser environment. It is applied first to all instances in all contexts. @example YUI.GlobalConfig = { filter: 'debug' }; YUI().use('node', function (Y) { // debug files used here }); YUI({ filter: 'min' }).use('node', function (Y) { // min files used here }); @property {Object} GlobalConfig @global @static **/ if (YUI.GlobalConfig) { Y.applyConfig(YUI.GlobalConfig); } /** Page-level config applied to all YUI instances created on the current page. This is applied after `YUI.GlobalConfig` and before any instance-level configuration. @example // Single global var to include before YUI seed file YUI_config = { filter: 'debug' }; YUI().use('node', function (Y) { // debug files used here }); YUI({ filter: 'min' }).use('node', function (Y) { // min files used here }); @property {Object} YUI_config @global **/ if (gconf) { Y.applyConfig(gconf); } // bind the specified additional modules for this instance if (!l) { Y._setup(); } } if (l) { // Each instance can accept one or more configuration objects. // These are applied after YUI.GlobalConfig and YUI_Config, // overriding values set in those config files if there is a // matching property. for (; i < l; i++) { Y.applyConfig(args[i]); } Y._setup(); } Y.instanceOf = instanceOf; return Y; }; (function() { var proto, prop, VERSION = '@VERSION@', PERIOD = '.', BASE = 'http://yui.yahooapis.com/', /* These CSS class names can't be generated by getClassName since it is not available at the time they are being used. */ DOC_LABEL = 'yui3-js-enabled', CSS_STAMP_EL = 'yui3-css-stamp', NOOP = function() {}, SLICE = Array.prototype.slice, APPLY_TO_AUTH = { 'io.xdrReady': 1, // the functions applyTo 'io.xdrResponse': 1, // can call. this should 'SWF.eventHandler': 1 }, // be done at build time hasWin = (typeof window != 'undefined'), win = (hasWin) ? window : null, doc = (hasWin) ? win.document : null, docEl = doc && doc.documentElement, docClass = docEl && docEl.className, instances = {}, time = new Date().getTime(), add = function(el, type, fn, capture) { if (el && el.addEventListener) { el.addEventListener(type, fn, capture); } else if (el && el.attachEvent) { el.attachEvent('on' + type, fn); } }, remove = function(el, type, fn, capture) { if (el && el.removeEventListener) { // this can throw an uncaught exception in FF try { el.removeEventListener(type, fn, capture); } catch (ex) {} } else if (el && el.detachEvent) { el.detachEvent('on' + type, fn); } }, handleLoad = function() { YUI.Env.windowLoaded = true; YUI.Env.DOMReady = true; if (hasWin) { remove(window, 'load', handleLoad); } }, getLoader = function(Y, o) { var loader = Y.Env._loader, lCore = [ 'loader-base' ], G_ENV = YUI.Env, mods = G_ENV.mods; if (loader) { //loader._config(Y.config); loader.ignoreRegistered = false; loader.onEnd = null; loader.data = null; loader.required = []; loader.loadType = null; } else { loader = new Y.Loader(Y.config); Y.Env._loader = loader; } if (mods && mods.loader) { lCore = [].concat(lCore, YUI.Env.loaderExtras); } YUI.Env.core = Y.Array.dedupe([].concat(YUI.Env.core, lCore)); return loader; }, clobber = function(r, s) { for (var i in s) { if (s.hasOwnProperty(i)) { r[i] = s[i]; } } }, ALREADY_DONE = { success: true }; // Stamp the documentElement (HTML) with a class of "yui-loaded" to // enable styles that need to key off of JS being enabled. if (docEl && docClass.indexOf(DOC_LABEL) == -1) { if (docClass) { docClass += ' '; } docClass += DOC_LABEL; docEl.className = docClass; } if (VERSION.indexOf('@') > -1) { VERSION = '3.5.0'; // dev time hack for cdn test } proto = { /** Applies a new configuration object to the config of this YUI instance. This will merge new group/module definitions, and will also update the loader cache if necessary. Updating `Y.config` directly will not update the cache. @method applyConfig @param {Object} o the configuration object. @since 3.2.0 **/ applyConfig: function(o) { o = o || NOOP; var attr, name, // detail, config = this.config, mods = config.modules, groups = config.groups, aliases = config.aliases, loader = this.Env._loader; for (name in o) { if (o.hasOwnProperty(name)) { attr = o[name]; if (mods && name == 'modules') { clobber(mods, attr); } else if (aliases && name == 'aliases') { clobber(aliases, attr); } else if (groups && name == 'groups') { clobber(groups, attr); } else if (name == 'win') { config[name] = (attr && attr.contentWindow) || attr; config.doc = config[name] ? config[name].document : null; } else if (name == '_yuid') { // preserve the guid } else { config[name] = attr; } } } if (loader) { loader._config(o); } }, /** Old way to apply a config to this instance (calls `applyConfig` under the hood). @private @method _config @param {Object} o The config to apply **/ _config: function(o) { this.applyConfig(o); }, /** Initializes this YUI instance. @private @method _init **/ _init: function() { var filter, el, Y = this, G_ENV = YUI.Env, Env = Y.Env, prop; /** The version number of this YUI instance. This value is typically updated by a script when a YUI release is built, so it may not reflect the correct version number when YUI is run from the development source tree. @property {String} version **/ Y.version = VERSION; if (!Env) { Y.Env = { core: ['get', 'features', 'intl-base', 'yui-log', 'yui-later'], loaderExtras: ['loader-rollup', 'loader-yui3'], mods: {}, // flat module map versions: {}, // version module map base: BASE, cdn: BASE + VERSION + '/build/', // bootstrapped: false, _idx: 0, _used: {}, _attached: {}, _missed: [], _yidx: 0, _uidx: 0, _guidp: 'y', _loaded: {}, // serviced: {}, // Regex in English: // I'll start at the \b(simpleyui). // 1. Look in the test string for "simpleyui" or "yui" or // "yui-base" or "yui-davglass" or "yui-foobar" that comes after a word break. That is, it // can't match "foyui" or "i_heart_simpleyui". This can be anywhere in the string. // 2. After #1 must come a forward slash followed by the string matched in #1, so // "yui-base/yui-base" or "simpleyui/simpleyui" or "yui-pants/yui-pants". // 3. The second occurence of the #1 token can optionally be followed by "-debug" or "-min", // so "yui/yui-min", "yui/yui-debug", "yui-base/yui-base-debug". NOT "yui/yui-tshirt". // 4. This is followed by ".js", so "yui/yui.js", "simpleyui/simpleyui-min.js" // 0. Going back to the beginning, now. If all that stuff in 1-4 comes after a "?" in the string, // then capture the junk between the LAST "&" and the string in 1-4. So // "blah?foo/yui/yui.js" will capture "foo/" and "blah?some/thing.js&3.3.0/build/yui-davglass/yui-davglass.js" // will capture "3.3.0/build/" // // Regex Exploded: // (?:\? Find a ? // (?:[^&]*&) followed by 0..n characters followed by an & // * in fact, find as many sets of characters followed by a & as you can // ([^&]*) capture the stuff after the last & in \1 // )? but it's ok if all this ?junk&more_junk stuff isn't even there // \b(simpleyui| after a word break find either the string "simpleyui" or // yui(?:-\w+)? the string "yui" optionally followed by a -, then more characters // ) and store the simpleyui or yui-* string in \2 // \/\2 then comes a / followed by the simpleyui or yui-* string in \2 // (?:-(min|debug))? optionally followed by "-min" or "-debug" // .js and ending in ".js" _BASE_RE: /(?:\?(?:[^&]*&)*([^&]*))?\b(simpleyui|yui(?:-\w+)?)\/\2(?:-(min|debug))?\.js/, parseBasePath: function(src, pattern) { var match = src.match(pattern), path, filter; if (match) { path = RegExp.leftContext || src.slice(0, src.indexOf(match[0])); // this is to set up the path to the loader. The file // filter for loader should match the yui include. filter = match[3]; // extract correct path for mixed combo urls // http://yuilibrary.com/projects/yui3/ticket/2528423 if (match[1]) { path += '?' + match[1]; } path = { filter: filter, path: path }; } return path; }, getBase: G_ENV && G_ENV.getBase || function(pattern) { var nodes = (doc && doc.getElementsByTagName('script')) || [], path = Env.cdn, parsed, i, len, src; for (i = 0, len = nodes.length; i < len; ++i) { src = nodes[i].src; if (src) { parsed = Y.Env.parseBasePath(src, pattern); if (parsed) { filter = parsed.filter; path = parsed.path; break; } } } // use CDN default return path; } }; Env = Y.Env; Env._loaded[VERSION] = {}; if (G_ENV && Y !== YUI) { Env._yidx = ++G_ENV._yidx; Env._guidp = ('yui_' + VERSION + '_' + Env._yidx + '_' + time).replace(/[^a-z0-9_]+/g, '_'); } else if (YUI._YUI) { G_ENV = YUI._YUI.Env; Env._yidx += G_ENV._yidx; Env._uidx += G_ENV._uidx; for (prop in G_ENV) { if (!(prop in Env)) { Env[prop] = G_ENV[prop]; } } delete YUI._YUI; } Y.id = Y.stamp(Y); instances[Y.id] = Y; } Y.constructor = YUI; // configuration defaults Y.config = Y.config || { bootstrap: true, cacheUse: true, debug: true, doc: doc, fetchCSS: true, throwFail: true, useBrowserConsole: true, useNativeES5: true, win: win, global: Function('return this')() }; //Register the CSS stamp element if (doc && !doc.getElementById(CSS_STAMP_EL)) { el = doc.createElement('div'); el.innerHTML = '<div id="' + CSS_STAMP_EL + '" style="position: absolute !important; visibility: hidden !important"></div>'; YUI.Env.cssStampEl = el.firstChild; if (doc.body) { doc.body.appendChild(YUI.Env.cssStampEl); } else { docEl.insertBefore(YUI.Env.cssStampEl, docEl.firstChild); } } else if (doc && doc.getElementById(CSS_STAMP_EL) && !YUI.Env.cssStampEl) { YUI.Env.cssStampEl = doc.getElementById(CSS_STAMP_EL); } Y.config.lang = Y.config.lang || 'en-US'; Y.config.base = YUI.config.base || Y.Env.getBase(Y.Env._BASE_RE); if (!filter || (!('mindebug').indexOf(filter))) { filter = 'min'; } filter = (filter) ? '-' + filter : filter; Y.config.loaderPath = YUI.config.loaderPath || 'loader/loader' + filter + '.js'; }, /** Finishes the instance setup. Attaches whatever YUI modules were defined at the time that this instance was created. @method _setup @private **/ _setup: function() { var i, Y = this, core = [], mods = YUI.Env.mods, extras = Y.config.core || [].concat(YUI.Env.core); //Clone it.. for (i = 0; i < extras.length; i++) { if (mods[extras[i]]) { core.push(extras[i]); } } Y._attach(['yui-base']); Y._attach(core); if (Y.Loader) { getLoader(Y); } }, /** Executes the named method on the specified YUI instance if that method is whitelisted. @method applyTo @param {String} id YUI instance id. @param {String} method Name of the method to execute. For example: 'Object.keys'. @param {Array} args Arguments to apply to the method. @return {Mixed} Return value from the applied method, or `null` if the specified instance was not found or the method was not whitelisted. **/ applyTo: function(id, method, args) { if (!(method in APPLY_TO_AUTH)) { this.log(method + ': applyTo not allowed', 'warn', 'yui'); return null; } var instance = instances[id], nest, m, i; if (instance) { nest = method.split('.'); m = instance; for (i = 0; i < nest.length; i = i + 1) { m = m[nest[i]]; if (!m) { this.log('applyTo not found: ' + method, 'warn', 'yui'); } } return m && m.apply(instance, args); } return null; }, /** Registers a YUI module and makes it available for use in a `YUI().use()` call or as a dependency for other modules. The easiest way to create a first-class YUI module is to use <a href="http://yui.github.com/shifter/">Shifter</a>, the YUI component build tool. Shifter will automatically wrap your module code in a `YUI.add()` call along with any configuration info required for the module. @example YUI.add('davglass', function (Y) { Y.davglass = function () { }; }, '3.4.0', { requires: ['harley-davidson', 'mt-dew'] }); @method add @param {String} name Module name. @param {Function} fn Function containing module code. This function will be executed whenever the module is attached to a specific YUI instance. @param {YUI} fn.Y The YUI instance to which this module is attached. @param {String} fn.name Name of the module @param {String} version Module version number. This is currently used only for informational purposes, and is not used internally by YUI. @param {Object} [config] Module config. @param {Array} [config.requires] Array of other module names that must be attached before this module can be attached. @param {Array} [config.optional] Array of optional module names that should be attached before this module is attached if they've already been loaded. If the `loadOptional` YUI option is `true`, optional modules that have not yet been loaded will be loaded just as if they were hard requirements. @param {Array} [config.use] Array of module names that are included within or otherwise provided by this module, and which should be attached automatically when this module is attached. This makes it possible to create "virtual rollup" modules that simply attach a collection of other modules or submodules. @return {YUI} This YUI instance. **/ add: function(name, fn, version, details) { details = details || {}; var env = YUI.Env, mod = { name: name, fn: fn, version: version, details: details }, //Instance hash so we don't apply it to the same instance twice applied = {}, loader, inst, i, versions = env.versions; env.mods[name] = mod; versions[version] = versions[version] || {}; versions[version][name] = mod; for (i in instances) { if (instances.hasOwnProperty(i)) { inst = instances[i]; if (!applied[inst.id]) { applied[inst.id] = true; loader = inst.Env._loader; if (loader) { if (!loader.moduleInfo[name] || loader.moduleInfo[name].temp) { loader.addModule(details, name); } } } } } return this; }, /** Executes the callback function associated with each required module, attaching the module to this YUI instance. @method _attach @param {Array} r The array of modules to attach @param {Boolean} [moot=false] If `true`, don't throw a warning if the module is not attached. @private **/ _attach: function(r, moot) { var i, name, mod, details, req, use, after, mods = YUI.Env.mods, aliases = YUI.Env.aliases, Y = this, j, cache = YUI.Env._renderedMods, loader = Y.Env._loader, done = Y.Env._attached, len = r.length, loader, def, go, c = []; //Check for conditional modules (in a second+ instance) and add their requirements //TODO I hate this entire method, it needs to be fixed ASAP (3.5.0) ^davglass for (i = 0; i < len; i++) { name = r[i]; mod = mods[name]; c.push(name); if (loader && loader.conditions[name]) { for (j in loader.conditions[name]) { if (loader.conditions[name].hasOwnProperty(j)) { def = loader.conditions[name][j]; go = def && ((def.ua && Y.UA[def.ua]) || (def.test && def.test(Y))); if (go) { c.push(def.name); } } } } } r = c; len = r.length; for (i = 0; i < len; i++) { if (!done[r[i]]) { name = r[i]; mod = mods[name]; if (aliases && aliases[name] && !mod) { Y._attach(aliases[name]); continue; } if (!mod) { if (loader && loader.moduleInfo[name]) { mod = loader.moduleInfo[name]; moot = true; } //if (!loader || !loader.moduleInfo[name]) { //if ((!loader || !loader.moduleInfo[name]) && !moot) { if (!moot && name) { if ((name.indexOf('skin-') === -1) && (name.indexOf('css') === -1)) { Y.Env._missed.push(name); Y.Env._missed = Y.Array.dedupe(Y.Env._missed); Y.message('NOT loaded: ' + name, 'warn', 'yui'); } } } else { done[name] = true; //Don't like this, but in case a mod was asked for once, then we fetch it //We need to remove it from the missed list ^davglass for (j = 0; j < Y.Env._missed.length; j++) { if (Y.Env._missed[j] === name) { Y.message('Found: ' + name + ' (was reported as missing earlier)', 'warn', 'yui'); Y.Env._missed.splice(j, 1); } } /* If it's a temp module, we need to redo it's requirements if it's already loaded since it may have been loaded by another instance and it's dependencies might have been redefined inside the fetched file. */ if (loader && cache && cache[name] && cache[name].temp) { loader.getRequires(cache[name]); req = []; for (j in loader.moduleInfo[name].expanded_map) { if (loader.moduleInfo[name].expanded_map.hasOwnProperty(j)) { req.push(j); } } Y._attach(req); } details = mod.details; req = details.requires; use = details.use; after = details.after; //Force Intl load if there is a language (Loader logic) @todo fix this shit if (details.lang) { req = req || []; req.unshift('intl'); } if (req) { for (j = 0; j < req.length; j++) { if (!done[req[j]]) { if (!Y._attach(req)) { return false; } break; } } } if (after) { for (j = 0; j < after.length; j++) { if (!done[after[j]]) { if (!Y._attach(after, true)) { return false; } break; } } } if (mod.fn) { if (Y.config.throwFail) { mod.fn(Y, name); } else { try { mod.fn(Y, name); } catch (e) { Y.error('Attach error: ' + name, e, name); return false; } } } if (use) { for (j = 0; j < use.length; j++) { if (!done[use[j]]) { if (!Y._attach(use)) { return false; } break; } } } } } } return true; }, /** Delays the `use` callback until another event has taken place such as `window.onload`, `domready`, `contentready`, or `available`. @private @method _delayCallback @param {Function} cb The original `use` callback. @param {String|Object} until Either an event name ('load', 'domready', etc.) or an object containing event/args keys for contentready/available. @return {Function} **/ _delayCallback: function(cb, until) { var Y = this, mod = ['event-base']; until = (Y.Lang.isObject(until) ? until : { event: until }); if (until.event === 'load') { mod.push('event-synthetic'); } return function() { var args = arguments; Y._use(mod, function() { Y.on(until.event, function() { args[1].delayUntil = until.event; cb.apply(Y, args); }, until.args); }); }; }, /** Attaches one or more modules to this YUI instance. When this is executed, the requirements of the desired modules are analyzed, and one of several things can happen: * All required modules have already been loaded, and just need to be attached to this YUI instance. In this case, the `use()` callback will be executed synchronously after the modules are attached. * One or more modules have not yet been loaded, or the Get utility is not available, or the `bootstrap` config option is `false`. In this case, a warning is issued indicating that modules are missing, but all available modules will still be attached and the `use()` callback will be executed synchronously. * One or more modules are missing and the Loader is not available but the Get utility is, and `bootstrap` is not `false`. In this case, the Get utility will be used to load the Loader, and we will then proceed to the following state: * One or more modules are missing and the Loader is available. In this case, the Loader will be used to resolve the dependency tree for the missing modules and load them and their dependencies. When the Loader is finished loading modules, the `use()` callback will be executed asynchronously. @example // Loads and attaches dd and its dependencies. YUI().use('dd', function (Y) { // ... }); // Loads and attaches dd and node as well as all of their dependencies. YUI().use(['dd', 'node'], function (Y) { // ... }); // Attaches all modules that have already been loaded. YUI().use('*', function (Y) { // ... }); // Attaches a gallery module. YUI().use('gallery-yql', function (Y) { // ... }); // Attaches a YUI 2in3 module. YUI().use('yui2-datatable', function (Y) { // ... }); @method use @param {String|Array} modules* One or more module names to attach. @param {Function} [callback] Callback function to be executed once all specified modules and their dependencies have been attached. @param {YUI} callback.Y The YUI instance created for this sandbox. @param {Object} callback.status Object containing `success`, `msg` and `data` properties. @chainable **/ use: function() { var args = SLICE.call(arguments, 0), callback = args[args.length - 1], Y = this, i = 0, name, Env = Y.Env, provisioned = true; // The last argument supplied to use can be a load complete callback if (Y.Lang.isFunction(callback)) { args.pop(); if (Y.config.delayUntil) { callback = Y._delayCallback(callback, Y.config.delayUntil); } } else { callback = null; } if (Y.Lang.isArray(args[0])) { args = args[0]; } if (Y.config.cacheUse) { while ((name = args[i++])) { if (!Env._attached[name]) { provisioned = false; break; } } if (provisioned) { if (args.length) { } Y._notify(callback, ALREADY_DONE, args); return Y; } } if (Y._loading) { Y._useQueue = Y._useQueue || new Y.Queue(); Y._useQueue.add([args, callback]); } else { Y._use(args, function(Y, response) { Y._notify(callback, response, args); }); } return Y; }, /** Handles Loader notifications about attachment/load errors. @method _notify @param {Function} callback Callback to pass to `Y.config.loadErrorFn`. @param {Object} response Response returned from Loader. @param {Array} args Arguments passed from Loader. @private **/ _notify: function(callback, response, args) { if (!response.success && this.config.loadErrorFn) { this.config.loadErrorFn.call(this, this, callback, response, args); } else if (callback) { if (this.Env._missed && this.Env._missed.length) { response.msg = 'Missing modules: ' + this.Env._missed.join(); response.success = false; } if (this.config.throwFail) { callback(this, response); } else { try { callback(this, response); } catch (e) { this.error('use callback error', e, args); } } } }, /** Called from the `use` method queue to ensure that only one set of loading logic is performed at a time. @method _use @param {String} args* One or more modules to attach. @param {Function} [callback] Function to call once all required modules have been attached. @private **/ _use: function(args, callback) { if (!this.Array) { this._attach(['yui-base']); } var len, loader, handleBoot, Y = this, G_ENV = YUI.Env, mods = G_ENV.mods, Env = Y.Env, used = Env._used, aliases = G_ENV.aliases, queue = G_ENV._loaderQueue, firstArg = args[0], YArray = Y.Array, config = Y.config, boot = config.bootstrap, missing = [], i, r = [], ret = true, fetchCSS = config.fetchCSS, process = function(names, skip) { var i = 0, a = [], name, len, m, req, use; if (!names.length) { return; } if (aliases) { len = names.length; for (i = 0; i < len; i++) { if (aliases[names[i]] && !mods[names[i]]) { a = [].concat(a, aliases[names[i]]); } else { a.push(names[i]); } } names = a; } len = names.length; for (i = 0; i < len; i++) { name = names[i]; if (!skip) { r.push(name); } // only attach a module once if (used[name]) { continue; } m = mods[name]; req = null; use = null; if (m) { used[name] = true; req = m.details.requires; use = m.details.use; } else { // CSS files don't register themselves, see if it has // been loaded if (!G_ENV._loaded[VERSION][name]) { missing.push(name); } else { used[name] = true; // probably css } } // make sure requirements are attached if (req && req.length) { process(req); } // make sure we grab the submodule dependencies too if (use && use.length) { process(use, 1); } } }, handleLoader = function(fromLoader) { var response = fromLoader || { success: true, msg: 'not dynamic' }, redo, origMissing, ret = true, data = response.data; Y._loading = false; if (data) { origMissing = missing; missing = []; r = []; process(data); redo = missing.length; if (redo) { if ([].concat(missing).sort().join() == origMissing.sort().join()) { redo = false; } } } if (redo && data) { Y._loading = true; Y._use(missing, function() { if (Y._attach(data)) { Y._notify(callback, response, data); } }); } else { if (data) { ret = Y._attach(data); } if (ret) { Y._notify(callback, response, args); } } if (Y._useQueue && Y._useQueue.size() && !Y._loading) { Y._use.apply(Y, Y._useQueue.next()); } }; // YUI().use('*'); // bind everything available if (firstArg === '*') { args = []; for (i in mods) { if (mods.hasOwnProperty(i)) { args.push(i); } } ret = Y._attach(args); if (ret) { handleLoader(); } return Y; } if ((mods.loader || mods['loader-base']) && !Y.Loader) { Y._attach(['loader' + ((!mods.loader) ? '-base' : '')]); } // use loader to expand dependencies and sort the // requirements if it is available. if (boot && Y.Loader && args.length) { loader = getLoader(Y); loader.require(args); loader.ignoreRegistered = true; loader._boot = true; loader.calculate(null, (fetchCSS) ? null : 'js'); args = loader.sorted; loader._boot = false; } process(args); len = missing.length; if (len) { missing = YArray.dedupe(missing); len = missing.length; } // dynamic load if (boot && len && Y.Loader) { Y._loading = true; loader = getLoader(Y); loader.onEnd = handleLoader; loader.context = Y; loader.data = args; loader.ignoreRegistered = false; loader.require(missing); loader.insert(null, (fetchCSS) ? null : 'js'); } else if (boot && len && Y.Get && !Env.bootstrapped) { Y._loading = true; handleBoot = function() { Y._loading = false; queue.running = false; Env.bootstrapped = true; G_ENV._bootstrapping = false; if (Y._attach(['loader'])) { Y._use(args, callback); } }; if (G_ENV._bootstrapping) { queue.add(handleBoot); } else { G_ENV._bootstrapping = true; Y.Get.script(config.base + config.loaderPath, { onEnd: handleBoot }); } } else { ret = Y._attach(args); if (ret) { handleLoader(); } } return Y; }, /** Utility method for safely creating namespaces if they don't already exist. May be called statically on the YUI global object or as a method on a YUI instance. When called statically, a namespace will be created on the YUI global object: // Create `YUI.your.namespace.here` as nested objects, preserving any // objects that already exist instead of overwriting them. YUI.namespace('your.namespace.here'); When called as a method on a YUI instance, a namespace will be created on that instance: // Creates `Y.property.package`. Y.namespace('property.package'); Dots in the input string cause `namespace` to create nested objects for each token. If any part of the requested namespace already exists, the current object will be left in place and will not be overwritten. This allows multiple calls to `namespace` to preserve existing namespaced properties. If the first token in the namespace string is "YAHOO", that token is discarded. This is legacy behavior for backwards compatibility with YUI 2. Be careful with namespace tokens. Reserved words may work in some browsers and not others. For instance, the following will fail in some browsers because the supported version of JavaScript reserves the word "long": Y.namespace('really.long.nested.namespace'); Note: If you pass multiple arguments to create multiple namespaces, only the last one created is returned from this function. @method namespace @param {String} namespace* One or more namespaces to create. @return {Object} Reference to the last namespace object created. **/ namespace: function() { var a = arguments, o, i = 0, j, d, arg; for (; i < a.length; i++) { o = this; //Reset base object per argument or it will get reused from the last arg = a[i]; if (arg.indexOf(PERIOD) > -1) { //Skip this if no "." is present d = arg.split(PERIOD); for (j = (d[0] == 'YAHOO') ? 1 : 0; j < d.length; j++) { o[d[j]] = o[d[j]] || {}; o = o[d[j]]; } } else { o[arg] = o[arg] || {}; o = o[arg]; //Reset base object to the new object so it's returned } } return o; }, // this is replaced if the log module is included log: NOOP, message: NOOP, // this is replaced if the dump module is included dump: function (o) { return ''+o; }, /** Reports an error. The reporting mechanism is controlled by the `throwFail` configuration attribute. If `throwFail` is falsy, the message is logged. If `throwFail` is truthy, a JS exception is thrown. If an `errorFn` is specified in the config it must return `true` to indicate that the exception was handled and keep it from being thrown. @method error @param {String} msg Error message. @param {Error|String} [e] JavaScript error object or an error string. @param {String} [src] Source of the error (such as the name of the module in which the error occurred). @chainable **/ error: function(msg, e, src) { //TODO Add check for window.onerror here var Y = this, ret; if (Y.config.errorFn) { ret = Y.config.errorFn.apply(Y, arguments); } if (!ret) { throw (e || new Error(msg)); } else { Y.message(msg, 'error', ''+src); // don't scrub this one } return Y; }, /** Generates an id string that is unique among all YUI instances in this execution context. @method guid @param {String} [pre] Prefix. @return {String} Unique id. **/ guid: function(pre) { var id = this.Env._guidp + '_' + (++this.Env._uidx); return (pre) ? (pre + id) : id; }, /** Returns a unique id associated with the given object and (if *readOnly* is falsy) stamps the object with that id so it can be identified in the future. Stamping an object involves adding a `_yuid` property to it that contains the object's id. One exception to this is that in Internet Explorer, DOM nodes have a `uniqueID` property that contains a browser-generated unique id, which will be used instead of a YUI-generated id when available. @method stamp @param {Object} o Object to stamp. @param {Boolean} readOnly If truthy and the given object has not already been stamped, the object will not be modified and `null` will be returned. @return {String} Object's unique id, or `null` if *readOnly* was truthy and the given object was not already stamped. **/ stamp: function(o, readOnly) { var uid; if (!o) { return o; } // IE generates its own unique ID for dom nodes // The uniqueID property of a document node returns a new ID if (o.uniqueID && o.nodeType && o.nodeType !== 9) { uid = o.uniqueID; } else { uid = (typeof o === 'string') ? o : o._yuid; } if (!uid) { uid = this.guid(); if (!readOnly) { try { o._yuid = uid; } catch (e) { uid = null; } } } return uid; }, /** Destroys this YUI instance. @method destroy @since 3.3.0 **/ destroy: function() { var Y = this; if (Y.Event) { Y.Event._unload(); } delete instances[Y.id]; delete Y.Env; delete Y.config; } /** Safe `instanceof` wrapper that works around a memory leak in IE when the object being tested is `window` or `document`. Unless you are testing objects that may be `window` or `document`, you should use the native `instanceof` operator instead of this method. @method instanceOf @param {Object} o Object to check. @param {Object} type Class to check against. @since 3.3.0 **/ }; YUI.prototype = proto; // inheritance utilities are not available yet for (prop in proto) { if (proto.hasOwnProperty(prop)) { YUI[prop] = proto[prop]; } } /** Applies a configuration to all YUI instances in this execution context. The main use case for this method is in "mashups" where several third-party scripts need to write to a global YUI config, but cannot share a single centrally-managed config object. This way they can all call `YUI.applyConfig({})` instead of overwriting the single global config. @example YUI.applyConfig({ modules: { davglass: { fullpath: './davglass.js' } } }); YUI.applyConfig({ modules: { foo: { fullpath: './foo.js' } } }); YUI().use('davglass', function (Y) { // Module davglass will be available here. }); @method applyConfig @param {Object} o Configuration object to apply. @static @since 3.5.0 **/ YUI.applyConfig = function(o) { if (!o) { return; } //If there is a GlobalConfig, apply it first to set the defaults if (YUI.GlobalConfig) { this.prototype.applyConfig.call(this, YUI.GlobalConfig); } //Apply this config to it this.prototype.applyConfig.call(this, o); //Reset GlobalConfig to the combined config YUI.GlobalConfig = this.config; }; // set up the environment YUI._init(); if (hasWin) { // add a window load event at load time so we can capture // the case where it fires before dynamic loading is // complete. add(window, 'load', handleLoad); } else { handleLoad(); } YUI.Env.add = add; YUI.Env.remove = remove; /*global exports*/ // Support the CommonJS method for exporting our single global if (typeof exports == 'object') { exports.YUI = YUI; /** * Set a method to be called when `Get.script` is called in Node.js * `Get` will open the file, then pass it's content and it's path * to this method before attaching it. Commonly used for code coverage * instrumentation. <strong>Calling this multiple times will only * attach the last hook method</strong>. This method is only * available in Node.js. * @method setLoadHook * @static * @param {Function} fn The function to set * @param {String} fn.data The content of the file * @param {String} fn.path The file path of the file */ YUI.setLoadHook = function(fn) { YUI._getLoadHook = fn; }; /** * Load hook for `Y.Get.script` in Node.js, see `YUI.setLoadHook` * @method _getLoadHook * @private * @param {String} data The content of the file * @param {String} path The file path of the file */ YUI._getLoadHook = null; } }()); /** Config object that contains all of the configuration options for this `YUI` instance. This object is supplied by the implementer when instantiating YUI. Some properties have default values if they are not supplied by the implementer. This object should not be updated directly because some values are cached. Use `applyConfig()` to update the config object on a YUI instance that has already been configured. @class config @static **/ /** If `true` (the default), YUI will "bootstrap" the YUI Loader and module metadata if they're needed to load additional dependencies and aren't already available. Setting this to `false` will prevent YUI from automatically loading the Loader and module metadata, so you will need to manually ensure that they're available or handle dependency resolution yourself. @property {Boolean} bootstrap @default true **/ /** @property {Object} aliases **/ /** A hash of module group definitions. For each group you can specify a list of modules and the base path and combo spec to use when dynamically loading the modules. @example groups: { yui2: { // specify whether or not this group has a combo service combine: true, // The comboSeperator to use with this group's combo handler comboSep: ';', // The maxURLLength for this server maxURLLength: 500, // the base path for non-combo paths base: 'http://yui.yahooapis.com/2.8.0r4/build/', // the path to the combo service comboBase: 'http://yui.yahooapis.com/combo?', // a fragment to prepend to the path attribute when // when building combo urls root: '2.8.0r4/build/', // the module definitions modules: { yui2_yde: { path: "yahoo-dom-event/yahoo-dom-event.js" }, yui2_anim: { path: "animation/animation.js", requires: ['yui2_yde'] } } } } @property {Object} groups **/ /** Path to the Loader JS file, relative to the `base` path. This is used to dynamically bootstrap the Loader when it's needed and isn't yet available. @property {String} loaderPath @default "loader/loader-min.js" **/ /** If `true`, YUI will attempt to load CSS dependencies and skins. Set this to `false` to prevent YUI from loading any CSS, or set it to the string `"force"` to force CSS dependencies to be loaded even if their associated JS modules are already loaded. @property {Boolean|String} fetchCSS @default true **/ /** Default gallery version used to build gallery module urls. @property {String} gallery @since 3.1.0 **/ /** Default YUI 2 version used to build YUI 2 module urls. This is used for intrinsic YUI 2 support via the 2in3 project. Also see the `2in3` config for pulling different revisions of the wrapped YUI 2 modules. @property {String} yui2 @default "2.9.0" @since 3.1.0 **/ /** Revision number of YUI 2in3 modules that should be used when loading YUI 2in3. @property {String} 2in3 @default "4" @since 3.1.0 **/ /** Alternate console log function that should be used in environments without a supported native console. This function is executed with the YUI instance as its `this` object. @property {Function} logFn @since 3.1.0 **/ /** The minimum log level to log messages for. Log levels are defined incrementally. Messages greater than or equal to the level specified will be shown. All others will be discarded. The order of log levels in increasing priority is: debug info warn error @property {String} logLevel @default 'debug' @since 3.10.0 **/ /** Callback to execute when `Y.error()` is called. It receives the error message and a JavaScript error object if one was provided. This function is executed with the YUI instance as its `this` object. Returning `true` from this function will prevent an exception from being thrown. @property {Function} errorFn @param {String} errorFn.msg Error message @param {Object} [errorFn.err] Error object (if one was provided). @since 3.2.0 **/ /** A callback to execute when Loader fails to load one or more resources. This could be because of a script load failure. It could also be because a module fails to register itself when the `requireRegistration` config is `true`. If this function is defined, the `use()` callback will only be called when the loader succeeds. Otherwise, `use()` will always executes unless there was a JavaScript error when attaching a module. @property {Function} loadErrorFn @since 3.3.0 **/ /** If `true`, Loader will expect all loaded scripts to be first-class YUI modules that register themselves with the YUI global, and will trigger a failure if a loaded script does not register a YUI module. @property {Boolean} requireRegistration @default false @since 3.3.0 **/ /** Cache serviced use() requests. @property {Boolean} cacheUse @default true @since 3.3.0 @deprecated No longer used. **/ /** Whether or not YUI should use native ES5 functionality when available for features like `Y.Array.each()`, `Y.Object()`, etc. When `false`, YUI will always use its own fallback implementations instead of relying on ES5 functionality, even when ES5 functionality is available. @property {Boolean} useNativeES5 @default true @since 3.5.0 **/ /** * Leverage native JSON stringify if the browser has a native * implementation. In general, this is a good idea. See the Known Issues * section in the JSON user guide for caveats. The default value is true * for browsers with native JSON support. * * @property useNativeJSONStringify * @type Boolean * @default true * @since 3.8.0 */ /** * Leverage native JSON parse if the browser has a native implementation. * In general, this is a good idea. See the Known Issues section in the * JSON user guide for caveats. The default value is true for browsers with * native JSON support. * * @property useNativeJSONParse * @type Boolean * @default true * @since 3.8.0 */ /** Delay the `use` callback until a specific event has passed (`load`, `domready`, `contentready` or `available`) @property delayUntil @type String|Object @since 3.6.0 @example You can use `load` or `domready` strings by default: YUI({ delayUntil: 'domready' }, function (Y) { // This will not execute until 'domeready' occurs. }); Or you can delay until a node is available (with `available` or `contentready`): YUI({ delayUntil: { event: 'available', args : '#foo' } }, function (Y) { // This will not execute until a node matching the selector "#foo" is // available in the DOM. }); @property {Object|String} delayUntil @since 3.6.0 **/ YUI.add('yui-base', function (Y, NAME) { /* * YUI stub * @module yui * @submodule yui-base */ /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Provides core language utilites and extensions used throughout YUI. * * @class Lang * @static */ var L = Y.Lang || (Y.Lang = {}), STRING_PROTO = String.prototype, TOSTRING = Object.prototype.toString, TYPES = { 'undefined' : 'undefined', 'number' : 'number', 'boolean' : 'boolean', 'string' : 'string', '[object Function]': 'function', '[object RegExp]' : 'regexp', '[object Array]' : 'array', '[object Date]' : 'date', '[object Error]' : 'error' }, SUBREGEX = /\{\s*([^|}]+?)\s*(?:\|([^}]*))?\s*\}/g, TRIMREGEX = /^\s+|\s+$/g, NATIVE_FN_REGEX = /\{\s*\[(?:native code|function)\]\s*\}/i; // -- Protected Methods -------------------------------------------------------- /** Returns `true` if the given function appears to be implemented in native code, `false` otherwise. Will always return `false` -- even in ES5-capable browsers -- if the `useNativeES5` YUI config option is set to `false`. This isn't guaranteed to be 100% accurate and won't work for anything other than functions, but it can be useful for determining whether a function like `Array.prototype.forEach` is native or a JS shim provided by another library. There's a great article by @kangax discussing certain flaws with this technique: <http://perfectionkills.com/detecting-built-in-host-methods/> While his points are valid, it's still possible to benefit from this function as long as it's used carefully and sparingly, and in such a way that false negatives have minimal consequences. It's used internally to avoid using potentially broken non-native ES5 shims that have been added to the page by other libraries. @method _isNative @param {Function} fn Function to test. @return {Boolean} `true` if _fn_ appears to be native, `false` otherwise. @static @protected @since 3.5.0 **/ L._isNative = function (fn) { return !!(Y.config.useNativeES5 && fn && NATIVE_FN_REGEX.test(fn)); }; // -- Public Methods ----------------------------------------------------------- /** * Determines whether or not the provided item is an array. * * Returns `false` for array-like collections such as the function `arguments` * collection or `HTMLElement` collections. Use `Y.Array.test()` if you want to * test for an array-like collection. * * @method isArray * @param o The object to test. * @return {boolean} true if o is an array. * @static */ L.isArray = L._isNative(Array.isArray) ? Array.isArray : function (o) { return L.type(o) === 'array'; }; /** * Determines whether or not the provided item is a boolean. * @method isBoolean * @static * @param o The object to test. * @return {boolean} true if o is a boolean. */ L.isBoolean = function(o) { return typeof o === 'boolean'; }; /** * Determines whether or not the supplied item is a date instance. * @method isDate * @static * @param o The object to test. * @return {boolean} true if o is a date. */ L.isDate = function(o) { return L.type(o) === 'date' && o.toString() !== 'Invalid Date' && !isNaN(o); }; /** * <p> * Determines whether or not the provided item is a function. * Note: Internet Explorer thinks certain functions are objects: * </p> * * <pre> * var obj = document.createElement("object"); * Y.Lang.isFunction(obj.getAttribute) // reports false in IE * &nbsp; * var input = document.createElement("input"); // append to body * Y.Lang.isFunction(input.focus) // reports false in IE * </pre> * * <p> * You will have to implement additional tests if these functions * matter to you. * </p> * * @method isFunction * @static * @param o The object to test. * @return {boolean} true if o is a function. */ L.isFunction = function(o) { return L.type(o) === 'function'; }; /** * Determines whether or not the provided item is null. * @method isNull * @static * @param o The object to test. * @return {boolean} true if o is null. */ L.isNull = function(o) { return o === null; }; /** * Determines whether or not the provided item is a legal number. * @method isNumber * @static * @param o The object to test. * @return {boolean} true if o is a number. */ L.isNumber = function(o) { return typeof o === 'number' && isFinite(o); }; /** * Determines whether or not the provided item is of type object * or function. Note that arrays are also objects, so * <code>Y.Lang.isObject([]) === true</code>. * @method isObject * @static * @param o The object to test. * @param failfn {boolean} fail if the input is a function. * @return {boolean} true if o is an object. * @see isPlainObject */ L.isObject = function(o, failfn) { var t = typeof o; return (o && (t === 'object' || (!failfn && (t === 'function' || L.isFunction(o))))) || false; }; /** * Determines whether or not the provided item is a string. * @method isString * @static * @param o The object to test. * @return {boolean} true if o is a string. */ L.isString = function(o) { return typeof o === 'string'; }; /** * Determines whether or not the provided item is undefined. * @method isUndefined * @static * @param o The object to test. * @return {boolean} true if o is undefined. */ L.isUndefined = function(o) { return typeof o === 'undefined'; }; /** * A convenience method for detecting a legitimate non-null value. * Returns false for null/undefined/NaN, true for other values, * including 0/false/'' * @method isValue * @static * @param o The item to test. * @return {boolean} true if it is not null/undefined/NaN || false. */ L.isValue = function(o) { var t = L.type(o); switch (t) { case 'number': return isFinite(o); case 'null': // fallthru case 'undefined': return false; default: return !!t; } }; /** * Returns the current time in milliseconds. * * @method now * @return {Number} Current time in milliseconds. * @static * @since 3.3.0 */ L.now = Date.now || function () { return new Date().getTime(); }; /** * Lightweight version of <code>Y.substitute</code>. Uses the same template * structure as <code>Y.substitute</code>, but doesn't support recursion, * auto-object coersion, or formats. * @method sub * @param {string} s String to be modified. * @param {object} o Object containing replacement values. * @return {string} the substitute result. * @static * @since 3.2.0 */ L.sub = function(s, o) { return s.replace ? s.replace(SUBREGEX, function (match, key) { return L.isUndefined(o[key]) ? match : o[key]; }) : s; }; /** * Returns a string without any leading or trailing whitespace. If * the input is not a string, the input will be returned untouched. * @method trim * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trim = STRING_PROTO.trim ? function(s) { return s && s.trim ? s.trim() : s; } : function (s) { try { return s.replace(TRIMREGEX, ''); } catch (e) { return s; } }; /** * Returns a string without any leading whitespace. * @method trimLeft * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimLeft = STRING_PROTO.trimLeft ? function (s) { return s.trimLeft(); } : function (s) { return s.replace(/^\s+/, ''); }; /** * Returns a string without any trailing whitespace. * @method trimRight * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimRight = STRING_PROTO.trimRight ? function (s) { return s.trimRight(); } : function (s) { return s.replace(/\s+$/, ''); }; /** Returns one of the following strings, representing the type of the item passed in: * "array" * "boolean" * "date" * "error" * "function" * "null" * "number" * "object" * "regexp" * "string" * "undefined" Known issues: * `typeof HTMLElementCollection` returns function in Safari, but `Y.Lang.type()` reports "object", which could be a good thing -- but it actually caused the logic in <code>Y.Lang.isObject</code> to fail. @method type @param o the item to test. @return {string} the detected type. @static **/ L.type = function(o) { return TYPES[typeof o] || TYPES[TOSTRING.call(o)] || (o ? 'object' : 'null'); }; /** @module yui @submodule yui-base */ var Lang = Y.Lang, Native = Array.prototype, hasOwn = Object.prototype.hasOwnProperty; /** Provides utility methods for working with arrays. Additional array helpers can be found in the `collection` and `array-extras` modules. `Y.Array(thing)` returns a native array created from _thing_. Depending on _thing_'s type, one of the following will happen: * Arrays are returned unmodified unless a non-zero _startIndex_ is specified. * Array-like collections (see `Array.test()`) are converted to arrays. * For everything else, a new array is created with _thing_ as the sole item. Note: elements that are also collections, such as `<form>` and `<select>` elements, are not automatically converted to arrays. To force a conversion, pass `true` as the value of the _force_ parameter. @class Array @constructor @param {Any} thing The thing to arrayify. @param {Number} [startIndex=0] If non-zero and _thing_ is an array or array-like collection, a subset of items starting at the specified index will be returned. @param {Boolean} [force=false] If `true`, _thing_ will be treated as an array-like collection no matter what. @return {Array} A native array created from _thing_, according to the rules described above. **/ function YArray(thing, startIndex, force) { var len, result; /*jshint expr: true*/ startIndex || (startIndex = 0); if (force || YArray.test(thing)) { // IE throws when trying to slice HTMLElement collections. try { return Native.slice.call(thing, startIndex); } catch (ex) { result = []; for (len = thing.length; startIndex < len; ++startIndex) { result.push(thing[startIndex]); } return result; } } return [thing]; } Y.Array = YArray; /** Dedupes an array of strings, returning an array that's guaranteed to contain only one copy of a given string. This method differs from `Array.unique()` in that it's optimized for use only with strings, whereas `unique` may be used with other types (but is slower). Using `dedupe()` with non-string values may result in unexpected behavior. @method dedupe @param {String[]} array Array of strings to dedupe. @return {Array} Deduped copy of _array_. @static @since 3.4.0 **/ YArray.dedupe = function (array) { var hash = {}, results = [], i, item, len; for (i = 0, len = array.length; i < len; ++i) { item = array[i]; if (!hasOwn.call(hash, item)) { hash[item] = 1; results.push(item); } } return results; }; /** Executes the supplied function on each item in the array. This method wraps the native ES5 `Array.forEach()` method if available. @method each @param {Array} array Array to iterate. @param {Function} fn Function to execute on each item in the array. The function will receive the following arguments: @param {Any} fn.item Current array item. @param {Number} fn.index Current array index. @param {Array} fn.array Array being iterated. @param {Object} [thisObj] `this` object to use when calling _fn_. @return {YUI} The YUI instance. @static **/ YArray.each = YArray.forEach = Lang._isNative(Native.forEach) ? function (array, fn, thisObj) { Native.forEach.call(array || [], fn, thisObj || Y); return Y; } : function (array, fn, thisObj) { for (var i = 0, len = (array && array.length) || 0; i < len; ++i) { if (i in array) { fn.call(thisObj || Y, array[i], i, array); } } return Y; }; /** Alias for `each()`. @method forEach @static **/ /** Returns an object using the first array as keys and the second as values. If the second array is not provided, or if it doesn't contain the same number of values as the first array, then `true` will be used in place of the missing values. @example Y.Array.hash(['a', 'b', 'c'], ['foo', 'bar']); // => {a: 'foo', b: 'bar', c: true} @method hash @param {String[]} keys Array of strings to use as keys. @param {Array} [values] Array to use as values. @return {Object} Hash using the first array as keys and the second as values. @static **/ YArray.hash = function (keys, values) { var hash = {}, vlen = (values && values.length) || 0, i, len; for (i = 0, len = keys.length; i < len; ++i) { if (i in keys) { hash[keys[i]] = vlen > i && i in values ? values[i] : true; } } return hash; }; /** Returns the index of the first item in the array that's equal (using a strict equality check) to the specified _value_, or `-1` if the value isn't found. This method wraps the native ES5 `Array.indexOf()` method if available. @method indexOf @param {Array} array Array to search. @param {Any} value Value to search for. @param {Number} [from=0] The index at which to begin the search. @return {Number} Index of the item strictly equal to _value_, or `-1` if not found. @static **/ YArray.indexOf = Lang._isNative(Native.indexOf) ? function (array, value, from) { return Native.indexOf.call(array, value, from); } : function (array, value, from) { // http://es5.github.com/#x15.4.4.14 var len = array.length; from = +from || 0; from = (from > 0 || -1) * Math.floor(Math.abs(from)); if (from < 0) { from += len; if (from < 0) { from = 0; } } for (; from < len; ++from) { if (from in array && array[from] === value) { return from; } } return -1; }; /** Numeric sort convenience function. The native `Array.prototype.sort()` function converts values to strings and sorts them in lexicographic order, which is unsuitable for sorting numeric values. Provide `Array.numericSort` as a custom sort function when you want to sort values in numeric order. @example [42, 23, 8, 16, 4, 15].sort(Y.Array.numericSort); // => [4, 8, 15, 16, 23, 42] @method numericSort @param {Number} a First value to compare. @param {Number} b Second value to compare. @return {Number} Difference between _a_ and _b_. @static **/ YArray.numericSort = function (a, b) { return a - b; }; /** Executes the supplied function on each item in the array. Returning a truthy value from the function will stop the processing of remaining items. @method some @param {Array} array Array to iterate over. @param {Function} fn Function to execute on each item. The function will receive the following arguments: @param {Any} fn.value Current array item. @param {Number} fn.index Current array index. @param {Array} fn.array Array being iterated over. @param {Object} [thisObj] `this` object to use when calling _fn_. @return {Boolean} `true` if the function returns a truthy value on any of the items in the array; `false` otherwise. @static **/ YArray.some = Lang._isNative(Native.some) ? function (array, fn, thisObj) { return Native.some.call(array, fn, thisObj); } : function (array, fn, thisObj) { for (var i = 0, len = array.length; i < len; ++i) { if (i in array && fn.call(thisObj, array[i], i, array)) { return true; } } return false; }; /** Evaluates _obj_ to determine if it's an array, an array-like collection, or something else. This is useful when working with the function `arguments` collection and `HTMLElement` collections. Note: This implementation doesn't consider elements that are also collections, such as `<form>` and `<select>`, to be array-like. @method test @param {Object} obj Object to test. @return {Number} A number indicating the results of the test: * 0: Neither an array nor an array-like collection. * 1: Real array. * 2: Array-like collection. @static **/ YArray.test = function (obj) { var result = 0; if (Lang.isArray(obj)) { result = 1; } else if (Lang.isObject(obj)) { try { // indexed, but no tagName (element) or scrollTo/document (window. From DOM.isWindow test which we can't use here), // or functions without apply/call (Safari // HTMLElementCollection bug). if ('length' in obj && !obj.tagName && !(obj.scrollTo && obj.document) && !obj.apply) { result = 2; } } catch (ex) {} } return result; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * A simple FIFO queue. Items are added to the Queue with add(1..n items) and * removed using next(). * * @class Queue * @constructor * @param {MIXED} item* 0..n items to seed the queue. */ function Queue() { this._init(); this.add.apply(this, arguments); } Queue.prototype = { /** * Initialize the queue * * @method _init * @protected */ _init: function() { /** * The collection of enqueued items * * @property _q * @type Array * @protected */ this._q = []; }, /** * Get the next item in the queue. FIFO support * * @method next * @return {MIXED} the next item in the queue. */ next: function() { return this._q.shift(); }, /** * Get the last in the queue. LIFO support. * * @method last * @return {MIXED} the last item in the queue. */ last: function() { return this._q.pop(); }, /** * Add 0..n items to the end of the queue. * * @method add * @param {MIXED} item* 0..n items. * @return {object} this queue. */ add: function() { this._q.push.apply(this._q, arguments); return this; }, /** * Returns the current number of queued items. * * @method size * @return {Number} The size. */ size: function() { return this._q.length; } }; Y.Queue = Queue; YUI.Env._loaderQueue = YUI.Env._loaderQueue || new Queue(); /** The YUI module contains the components required for building the YUI seed file. This includes the script loading mechanism, a simple queue, and the core utilities for the library. @module yui @submodule yui-base **/ var CACHED_DELIMITER = '__', hasOwn = Object.prototype.hasOwnProperty, isObject = Y.Lang.isObject; /** Returns a wrapper for a function which caches the return value of that function, keyed off of the combined string representation of the argument values provided when the wrapper is called. Calling this function again with the same arguments will return the cached value rather than executing the wrapped function. Note that since the cache is keyed off of the string representation of arguments passed to the wrapper function, arguments that aren't strings and don't provide a meaningful `toString()` method may result in unexpected caching behavior. For example, the objects `{}` and `{foo: 'bar'}` would both be converted to the string `[object Object]` when used as a cache key. @method cached @param {Function} source The function to memoize. @param {Object} [cache={}] Object in which to store cached values. You may seed this object with pre-existing cached values if desired. @param {any} [refetch] If supplied, this value is compared with the cached value using a `==` comparison. If the values are equal, the wrapped function is executed again even though a cached value exists. @return {Function} Wrapped function. @for YUI **/ Y.cached = function (source, cache, refetch) { /*jshint expr: true*/ cache || (cache = {}); return function (arg) { var key = arguments.length > 1 ? Array.prototype.join.call(arguments, CACHED_DELIMITER) : String(arg); /*jshint eqeqeq: false*/ if (!(key in cache) || (refetch && cache[key] == refetch)) { cache[key] = source.apply(source, arguments); } return cache[key]; }; }; /** Returns the `location` object from the window/frame in which this YUI instance operates, or `undefined` when executing in a non-browser environment (e.g. Node.js). It is _not_ recommended to hold references to the `window.location` object outside of the scope of a function in which its properties are being accessed or its methods are being called. This is because of a nasty bug/issue that exists in both Safari and MobileSafari browsers: [WebKit Bug 34679](https://bugs.webkit.org/show_bug.cgi?id=34679). @method getLocation @return {location} The `location` object from the window/frame in which this YUI instance operates. @since 3.5.0 **/ Y.getLocation = function () { // It is safer to look this up every time because yui-base is attached to a // YUI instance before a user's config is applied; i.e. `Y.config.win` does // not point the correct window object when this file is loaded. var win = Y.config.win; // It is not safe to hold a reference to the `location` object outside the // scope in which it is being used. The WebKit engine used in Safari and // MobileSafari will "disconnect" the `location` object from the `window` // when a page is restored from back/forward history cache. return win && win.location; }; /** Returns a new object containing all of the properties of all the supplied objects. The properties from later objects will overwrite those in earlier objects. Passing in a single object will create a shallow copy of it. For a deep copy, use `clone()`. @method merge @param {Object} objects* One or more objects to merge. @return {Object} A new merged object. **/ Y.merge = function () { var i = 0, len = arguments.length, result = {}, key, obj; for (; i < len; ++i) { obj = arguments[i]; for (key in obj) { if (hasOwn.call(obj, key)) { result[key] = obj[key]; } } } return result; }; /** Mixes _supplier_'s properties into _receiver_. Properties on _receiver_ or _receiver_'s prototype will not be overwritten or shadowed unless the _overwrite_ parameter is `true`, and will not be merged unless the _merge_ parameter is `true`. In the default mode (0), only properties the supplier owns are copied (prototype properties are not copied). The following copying modes are available: * `0`: _Default_. Object to object. * `1`: Prototype to prototype. * `2`: Prototype to prototype and object to object. * `3`: Prototype to object. * `4`: Object to prototype. @method mix @param {Function|Object} receiver The object or function to receive the mixed properties. @param {Function|Object} supplier The object or function supplying the properties to be mixed. @param {Boolean} [overwrite=false] If `true`, properties that already exist on the receiver will be overwritten with properties from the supplier. @param {String[]} [whitelist] An array of property names to copy. If specified, only the whitelisted properties will be copied, and all others will be ignored. @param {Number} [mode=0] Mix mode to use. See above for available modes. @param {Boolean} [merge=false] If `true`, objects and arrays that already exist on the receiver will have the corresponding object/array from the supplier merged into them, rather than being skipped or overwritten. When both _overwrite_ and _merge_ are `true`, _merge_ takes precedence. @return {Function|Object|YUI} The receiver, or the YUI instance if the specified receiver is falsy. **/ Y.mix = function(receiver, supplier, overwrite, whitelist, mode, merge) { var alwaysOverwrite, exists, from, i, key, len, to; // If no supplier is given, we return the receiver. If no receiver is given, // we return Y. Returning Y doesn't make much sense to me, but it's // grandfathered in for backcompat reasons. if (!receiver || !supplier) { return receiver || Y; } if (mode) { // In mode 2 (prototype to prototype and object to object), we recurse // once to do the proto to proto mix. The object to object mix will be // handled later on. if (mode === 2) { Y.mix(receiver.prototype, supplier.prototype, overwrite, whitelist, 0, merge); } // Depending on which mode is specified, we may be copying from or to // the prototypes of the supplier and receiver. from = mode === 1 || mode === 3 ? supplier.prototype : supplier; to = mode === 1 || mode === 4 ? receiver.prototype : receiver; // If either the supplier or receiver doesn't actually have a // prototype property, then we could end up with an undefined `from` // or `to`. If that happens, we abort and return the receiver. if (!from || !to) { return receiver; } } else { from = supplier; to = receiver; } // If `overwrite` is truthy and `merge` is falsy, then we can skip a // property existence check on each iteration and save some time. alwaysOverwrite = overwrite && !merge; if (whitelist) { for (i = 0, len = whitelist.length; i < len; ++i) { key = whitelist[i]; // We call `Object.prototype.hasOwnProperty` instead of calling // `hasOwnProperty` on the object itself, since the object's // `hasOwnProperty` method may have been overridden or removed. // Also, some native objects don't implement a `hasOwnProperty` // method. if (!hasOwn.call(from, key)) { continue; } // The `key in to` check here is (sadly) intentional for backwards // compatibility reasons. It prevents undesired shadowing of // prototype members on `to`. exists = alwaysOverwrite ? false : key in to; if (merge && exists && isObject(to[key], true) && isObject(from[key], true)) { // If we're in merge mode, and the key is present on both // objects, and the value on both objects is either an object or // an array (but not a function), then we recurse to merge the // `from` value into the `to` value instead of overwriting it. // // Note: It's intentional that the whitelist isn't passed to the // recursive call here. This is legacy behavior that lots of // code still depends on. Y.mix(to[key], from[key], overwrite, null, 0, merge); } else if (overwrite || !exists) { // We're not in merge mode, so we'll only copy the `from` value // to the `to` value if we're in overwrite mode or if the // current key doesn't exist on the `to` object. to[key] = from[key]; } } } else { for (key in from) { // The code duplication here is for runtime performance reasons. // Combining whitelist and non-whitelist operations into a single // loop or breaking the shared logic out into a function both result // in worse performance, and Y.mix is critical enough that the byte // tradeoff is worth it. if (!hasOwn.call(from, key)) { continue; } // The `key in to` check here is (sadly) intentional for backwards // compatibility reasons. It prevents undesired shadowing of // prototype members on `to`. exists = alwaysOverwrite ? false : key in to; if (merge && exists && isObject(to[key], true) && isObject(from[key], true)) { Y.mix(to[key], from[key], overwrite, null, 0, merge); } else if (overwrite || !exists) { to[key] = from[key]; } } // If this is an IE browser with the JScript enumeration bug, force // enumeration of the buggy properties by making a recursive call with // the buggy properties as the whitelist. if (Y.Object._hasEnumBug) { Y.mix(to, from, overwrite, Y.Object._forceEnum, mode, merge); } } return receiver; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Adds utilities to the YUI instance for working with objects. * * @class Object */ var Lang = Y.Lang, hasOwn = Object.prototype.hasOwnProperty, UNDEFINED, // <-- Note the comma. We're still declaring vars. /** * Returns a new object that uses _obj_ as its prototype. This method wraps the * native ES5 `Object.create()` method if available, but doesn't currently * pass through `Object.create()`'s second argument (properties) in order to * ensure compatibility with older browsers. * * @method () * @param {Object} obj Prototype object. * @return {Object} New object using _obj_ as its prototype. * @static */ O = Y.Object = Lang._isNative(Object.create) ? function (obj) { // We currently wrap the native Object.create instead of simply aliasing it // to ensure consistency with our fallback shim, which currently doesn't // support Object.create()'s second argument (properties). Once we have a // safe fallback for the properties arg, we can stop wrapping // Object.create(). return Object.create(obj); } : (function () { // Reusable constructor function for the Object.create() shim. function F() {} // The actual shim. return function (obj) { F.prototype = obj; return new F(); }; }()), /** * Property names that IE doesn't enumerate in for..in loops, even when they * should be enumerable. When `_hasEnumBug` is `true`, it's necessary to * manually enumerate these properties. * * @property _forceEnum * @type String[] * @protected * @static */ forceEnum = O._forceEnum = [ 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toString', 'toLocaleString', 'valueOf' ], /** * `true` if this browser has the JScript enumeration bug that prevents * enumeration of the properties named in the `_forceEnum` array, `false` * otherwise. * * See: * - <https://developer.mozilla.org/en/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug> * - <http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation> * * @property _hasEnumBug * @type Boolean * @protected * @static */ hasEnumBug = O._hasEnumBug = !{valueOf: 0}.propertyIsEnumerable('valueOf'), /** * `true` if this browser incorrectly considers the `prototype` property of * functions to be enumerable. Currently known to affect Opera 11.50. * * @property _hasProtoEnumBug * @type Boolean * @protected * @static */ hasProtoEnumBug = O._hasProtoEnumBug = (function () {}).propertyIsEnumerable('prototype'), /** * Returns `true` if _key_ exists on _obj_, `false` if _key_ doesn't exist or * exists only on _obj_'s prototype. This is essentially a safer version of * `obj.hasOwnProperty()`. * * @method owns * @param {Object} obj Object to test. * @param {String} key Property name to look for. * @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise. * @static */ owns = O.owns = function (obj, key) { return !!obj && hasOwn.call(obj, key); }; // <-- End of var declarations. /** * Alias for `owns()`. * * @method hasKey * @param {Object} obj Object to test. * @param {String} key Property name to look for. * @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise. * @static */ O.hasKey = owns; /** * Returns an array containing the object's enumerable keys. Does not include * prototype keys or non-enumerable keys. * * Note that keys are returned in enumeration order (that is, in the same order * that they would be enumerated by a `for-in` loop), which may not be the same * as the order in which they were defined. * * This method is an alias for the native ES5 `Object.keys()` method if * available. * * @example * * Y.Object.keys({a: 'foo', b: 'bar', c: 'baz'}); * // => ['a', 'b', 'c'] * * @method keys * @param {Object} obj An object. * @return {String[]} Array of keys. * @static */ O.keys = Lang._isNative(Object.keys) ? Object.keys : function (obj) { if (!Lang.isObject(obj)) { throw new TypeError('Object.keys called on a non-object'); } var keys = [], i, key, len; if (hasProtoEnumBug && typeof obj === 'function') { for (key in obj) { if (owns(obj, key) && key !== 'prototype') { keys.push(key); } } } else { for (key in obj) { if (owns(obj, key)) { keys.push(key); } } } if (hasEnumBug) { for (i = 0, len = forceEnum.length; i < len; ++i) { key = forceEnum[i]; if (owns(obj, key)) { keys.push(key); } } } return keys; }; /** * Returns an array containing the values of the object's enumerable keys. * * Note that values are returned in enumeration order (that is, in the same * order that they would be enumerated by a `for-in` loop), which may not be the * same as the order in which they were defined. * * @example * * Y.Object.values({a: 'foo', b: 'bar', c: 'baz'}); * // => ['foo', 'bar', 'baz'] * * @method values * @param {Object} obj An object. * @return {Array} Array of values. * @static */ O.values = function (obj) { var keys = O.keys(obj), i = 0, len = keys.length, values = []; for (; i < len; ++i) { values.push(obj[keys[i]]); } return values; }; /** * Returns the number of enumerable keys owned by an object. * * @method size * @param {Object} obj An object. * @return {Number} The object's size. * @static */ O.size = function (obj) { try { return O.keys(obj).length; } catch (ex) { return 0; // Legacy behavior for non-objects. } }; /** * Returns `true` if the object owns an enumerable property with the specified * value. * * @method hasValue * @param {Object} obj An object. * @param {any} value The value to search for. * @return {Boolean} `true` if _obj_ contains _value_, `false` otherwise. * @static */ O.hasValue = function (obj, value) { return Y.Array.indexOf(O.values(obj), value) > -1; }; /** * Executes a function on each enumerable property in _obj_. The function * receives the value, the key, and the object itself as parameters (in that * order). * * By default, only properties owned by _obj_ are enumerated. To include * prototype properties, set the _proto_ parameter to `true`. * * @method each * @param {Object} obj Object to enumerate. * @param {Function} fn Function to execute on each enumerable property. * @param {mixed} fn.value Value of the current property. * @param {String} fn.key Key of the current property. * @param {Object} fn.obj Object being enumerated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @param {Boolean} [proto=false] Include prototype properties. * @return {YUI} the YUI instance. * @chainable * @static */ O.each = function (obj, fn, thisObj, proto) { var key; for (key in obj) { if (proto || owns(obj, key)) { fn.call(thisObj || Y, obj[key], key, obj); } } return Y; }; /** * Executes a function on each enumerable property in _obj_, but halts if the * function returns a truthy value. The function receives the value, the key, * and the object itself as paramters (in that order). * * By default, only properties owned by _obj_ are enumerated. To include * prototype properties, set the _proto_ parameter to `true`. * * @method some * @param {Object} obj Object to enumerate. * @param {Function} fn Function to execute on each enumerable property. * @param {mixed} fn.value Value of the current property. * @param {String} fn.key Key of the current property. * @param {Object} fn.obj Object being enumerated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @param {Boolean} [proto=false] Include prototype properties. * @return {Boolean} `true` if any execution of _fn_ returns a truthy value, * `false` otherwise. * @static */ O.some = function (obj, fn, thisObj, proto) { var key; for (key in obj) { if (proto || owns(obj, key)) { if (fn.call(thisObj || Y, obj[key], key, obj)) { return true; } } } return false; }; /** * Retrieves the sub value at the provided path, * from the value object provided. * * @method getValue * @static * @param o The object from which to extract the property value. * @param path {Array} A path array, specifying the object traversal path * from which to obtain the sub value. * @return {Any} The value stored in the path, undefined if not found, * undefined if the source is not an object. Returns the source object * if an empty path is provided. */ O.getValue = function(o, path) { if (!Lang.isObject(o)) { return UNDEFINED; } var i, p = Y.Array(path), l = p.length; for (i = 0; o !== UNDEFINED && i < l; i++) { o = o[p[i]]; } return o; }; /** * Sets the sub-attribute value at the provided path on the * value object. Returns the modified value object, or * undefined if the path is invalid. * * @method setValue * @static * @param o The object on which to set the sub value. * @param path {Array} A path array, specifying the object traversal path * at which to set the sub value. * @param val {Any} The new value for the sub-attribute. * @return {Object} The modified object, with the new sub value set, or * undefined, if the path was invalid. */ O.setValue = function(o, path, val) { var i, p = Y.Array(path), leafIdx = p.length - 1, ref = o; if (leafIdx >= 0) { for (i = 0; ref !== UNDEFINED && i < leafIdx; i++) { ref = ref[p[i]]; } if (ref !== UNDEFINED) { ref[p[i]] = val; } else { return UNDEFINED; } } return o; }; /** * Returns `true` if the object has no enumerable properties of its own. * * @method isEmpty * @param {Object} obj An object. * @return {Boolean} `true` if the object is empty. * @static * @since 3.2.0 */ O.isEmpty = function (obj) { return !O.keys(Object(obj)).length; }; /** * The YUI module contains the components required for building the YUI seed * file. This includes the script loading mechanism, a simple queue, and the * core utilities for the library. * @module yui * @submodule yui-base */ /** * YUI user agent detection. * Do not fork for a browser if it can be avoided. Use feature detection when * you can. Use the user agent as a last resort. For all fields listed * as @type float, UA stores a version number for the browser engine, * 0 otherwise. This value may or may not map to the version number of * the browser using the engine. The value is presented as a float so * that it can easily be used for boolean evaluation as well as for * looking for a particular range of versions. Because of this, * some of the granularity of the version info may be lost. The fields that * are @type string default to null. The API docs list the values that * these fields can have. * @class UA * @static */ /** * Static method on `YUI.Env` for parsing a UA string. Called at instantiation * to populate `Y.UA`. * * @static * @method parseUA * @param {String} [subUA=navigator.userAgent] UA string to parse * @return {Object} The Y.UA object */ YUI.Env.parseUA = function(subUA) { var numberify = function(s) { var c = 0; return parseFloat(s.replace(/\./g, function() { return (c++ === 1) ? '' : '.'; })); }, win = Y.config.win, nav = win && win.navigator, o = { /** * Internet Explorer version number or 0. Example: 6 * @property ie * @type float * @static */ ie: 0, /** * Opera version number or 0. Example: 9.2 * @property opera * @type float * @static */ opera: 0, /** * Gecko engine revision number. Will evaluate to 1 if Gecko * is detected but the revision could not be found. Other browsers * will be 0. Example: 1.8 * <pre> * Firefox 1.0.0.4: 1.7.8 <-- Reports 1.7 * Firefox 1.5.0.9: 1.8.0.9 <-- 1.8 * Firefox 2.0.0.3: 1.8.1.3 <-- 1.81 * Firefox 3.0 <-- 1.9 * Firefox 3.5 <-- 1.91 * </pre> * @property gecko * @type float * @static */ gecko: 0, /** * AppleWebKit version. KHTML browsers that are not WebKit browsers * will evaluate to 1, other browsers 0. Example: 418.9 * <pre> * Safari 1.3.2 (312.6): 312.8.1 <-- Reports 312.8 -- currently the * latest available for Mac OSX 10.3. * Safari 2.0.2: 416 <-- hasOwnProperty introduced * Safari 2.0.4: 418 <-- preventDefault fixed * Safari 2.0.4 (419.3): 418.9.1 <-- One version of Safari may run * different versions of webkit * Safari 2.0.4 (419.3): 419 <-- Tiger installations that have been * updated, but not updated * to the latest patch. * Webkit 212 nightly: 522+ <-- Safari 3.0 precursor (with native * SVG and many major issues fixed). * Safari 3.0.4 (523.12) 523.12 <-- First Tiger release - automatic * update from 2.x via the 10.4.11 OS patch. * Webkit nightly 1/2008:525+ <-- Supports DOMContentLoaded event. * yahoo.com user agent hack removed. * </pre> * http://en.wikipedia.org/wiki/Safari_version_history * @property webkit * @type float * @static */ webkit: 0, /** * Safari will be detected as webkit, but this property will also * be populated with the Safari version number * @property safari * @type float * @static */ safari: 0, /** * Chrome will be detected as webkit, but this property will also * be populated with the Chrome version number * @property chrome * @type float * @static */ chrome: 0, /** * The mobile property will be set to a string containing any relevant * user agent information when a modern mobile browser is detected. * Currently limited to Safari on the iPhone/iPod Touch, Nokia N-series * devices with the WebKit-based browser, and Opera Mini. * @property mobile * @type string * @default null * @static */ mobile: null, /** * Adobe AIR version number or 0. Only populated if webkit is detected. * Example: 1.0 * @property air * @type float */ air: 0, /** * PhantomJS version number or 0. Only populated if webkit is detected. * Example: 1.0 * @property phantomjs * @type float */ phantomjs: 0, /** * Detects Apple iPad's OS version * @property ipad * @type float * @static */ ipad: 0, /** * Detects Apple iPhone's OS version * @property iphone * @type float * @static */ iphone: 0, /** * Detects Apples iPod's OS version * @property ipod * @type float * @static */ ipod: 0, /** * General truthy check for iPad, iPhone or iPod * @property ios * @type Boolean * @default null * @static */ ios: null, /** * Detects Googles Android OS version * @property android * @type float * @static */ android: 0, /** * Detects Kindle Silk * @property silk * @type float * @static */ silk: 0, /** * Detects Kindle Silk Acceleration * @property accel * @type Boolean * @static */ accel: false, /** * Detects Palms WebOS version * @property webos * @type float * @static */ webos: 0, /** * Google Caja version number or 0. * @property caja * @type float */ caja: nav && nav.cajaVersion, /** * Set to true if the page appears to be in SSL * @property secure * @type boolean * @static */ secure: false, /** * The operating system. Currently only detecting windows or macintosh * @property os * @type string * @default null * @static */ os: null, /** * The Nodejs Version * @property nodejs * @type float * @default 0 * @static */ nodejs: 0, /** * Window8/IE10 Application host environment * @property winjs * @type Boolean * @static */ winjs: !!((typeof Windows !== "undefined") && Windows.System), /** * Are touch/msPointer events available on this device * @property touchEnabled * @type Boolean * @static */ touchEnabled: false }, ua = subUA || nav && nav.userAgent, loc = win && win.location, href = loc && loc.href, m; /** * The User Agent string that was parsed * @property userAgent * @type String * @static */ o.userAgent = ua; o.secure = href && (href.toLowerCase().indexOf('https') === 0); if (ua) { if ((/windows|win32/i).test(ua)) { o.os = 'windows'; } else if ((/macintosh|mac_powerpc/i).test(ua)) { o.os = 'macintosh'; } else if ((/android/i).test(ua)) { o.os = 'android'; } else if ((/symbos/i).test(ua)) { o.os = 'symbos'; } else if ((/linux/i).test(ua)) { o.os = 'linux'; } else if ((/rhino/i).test(ua)) { o.os = 'rhino'; } // Modern KHTML browsers should qualify as Safari X-Grade if ((/KHTML/).test(ua)) { o.webkit = 1; } if ((/IEMobile|XBLWP7/).test(ua)) { o.mobile = 'windows'; } if ((/Fennec/).test(ua)) { o.mobile = 'gecko'; } // Modern WebKit browsers are at least X-Grade m = ua.match(/AppleWebKit\/([^\s]*)/); if (m && m[1]) { o.webkit = numberify(m[1]); o.safari = o.webkit; if (/PhantomJS/.test(ua)) { m = ua.match(/PhantomJS\/([^\s]*)/); if (m && m[1]) { o.phantomjs = numberify(m[1]); } } // Mobile browser check if (/ Mobile\//.test(ua) || (/iPad|iPod|iPhone/).test(ua)) { o.mobile = 'Apple'; // iPhone or iPod Touch m = ua.match(/OS ([^\s]*)/); if (m && m[1]) { m = numberify(m[1].replace('_', '.')); } o.ios = m; o.os = 'ios'; o.ipad = o.ipod = o.iphone = 0; m = ua.match(/iPad|iPod|iPhone/); if (m && m[0]) { o[m[0].toLowerCase()] = o.ios; } } else { m = ua.match(/NokiaN[^\/]*|webOS\/\d\.\d/); if (m) { // Nokia N-series, webOS, ex: NokiaN95 o.mobile = m[0]; } if (/webOS/.test(ua)) { o.mobile = 'WebOS'; m = ua.match(/webOS\/([^\s]*);/); if (m && m[1]) { o.webos = numberify(m[1]); } } if (/ Android/.test(ua)) { if (/Mobile/.test(ua)) { o.mobile = 'Android'; } m = ua.match(/Android ([^\s]*);/); if (m && m[1]) { o.android = numberify(m[1]); } } if (/Silk/.test(ua)) { m = ua.match(/Silk\/([^\s]*)\)/); if (m && m[1]) { o.silk = numberify(m[1]); } if (!o.android) { o.android = 2.34; //Hack for desktop mode in Kindle o.os = 'Android'; } if (/Accelerated=true/.test(ua)) { o.accel = true; } } } m = ua.match(/(Chrome|CrMo|CriOS)\/([^\s]*)/); if (m && m[1] && m[2]) { o.chrome = numberify(m[2]); // Chrome o.safari = 0; //Reset safari back to 0 if (m[1] === 'CrMo') { o.mobile = 'chrome'; } } else { m = ua.match(/AdobeAIR\/([^\s]*)/); if (m) { o.air = m[0]; // Adobe AIR 1.0 or better } } } if (!o.webkit) { // not webkit // @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr) if (/Opera/.test(ua)) { m = ua.match(/Opera[\s\/]([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); } m = ua.match(/Version\/([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); // opera 10+ } if (/Opera Mobi/.test(ua)) { o.mobile = 'opera'; m = ua.replace('Opera Mobi', '').match(/Opera ([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); } } m = ua.match(/Opera Mini[^;]*/); if (m) { o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316 } } else { // not opera or webkit m = ua.match(/MSIE\s([^;]*)/); if (m && m[1]) { o.ie = numberify(m[1]); } else { // not opera, webkit, or ie m = ua.match(/Gecko\/([^\s]*)/); if (m) { o.gecko = 1; // Gecko detected, look for revision m = ua.match(/rv:([^\s\)]*)/); if (m && m[1]) { o.gecko = numberify(m[1]); if (/Mobile|Tablet/.test(ua)) { o.mobile = "ffos"; } } } } } } } //Check for known properties to tell if touch events are enabled on this device or if //the number of MSPointer touchpoints on this device is greater than 0. if (win && nav && !(o.chrome && o.chrome < 6)) { o.touchEnabled = (("ontouchstart" in win) || (("msMaxTouchPoints" in nav) && (nav.msMaxTouchPoints > 0))); } //It was a parsed UA, do not assign the global value. if (!subUA) { if (typeof process === 'object') { if (process.versions && process.versions.node) { //NodeJS o.os = process.platform; o.nodejs = numberify(process.versions.node); } } YUI.Env.UA = o; } return o; }; Y.UA = YUI.Env.UA || YUI.Env.parseUA(); /** Performs a simple comparison between two version numbers, accounting for standard versioning logic such as the fact that "535.8" is a lower version than "535.24", even though a simple numerical comparison would indicate that it's greater. Also accounts for cases such as "1.1" vs. "1.1.0", which are considered equivalent. Returns -1 if version _a_ is lower than version _b_, 0 if they're equivalent, 1 if _a_ is higher than _b_. Versions may be numbers or strings containing numbers and dots. For example, both `535` and `"535.8.10"` are acceptable. A version string containing non-numeric characters, like `"535.8.beta"`, may produce unexpected results. @method compareVersions @param {Number|String} a First version number to compare. @param {Number|String} b Second version number to compare. @return -1 if _a_ is lower than _b_, 0 if they're equivalent, 1 if _a_ is higher than _b_. **/ Y.UA.compareVersions = function (a, b) { var aPart, aParts, bPart, bParts, i, len; if (a === b) { return 0; } aParts = (a + '').split('.'); bParts = (b + '').split('.'); for (i = 0, len = Math.max(aParts.length, bParts.length); i < len; ++i) { aPart = parseInt(aParts[i], 10); bPart = parseInt(bParts[i], 10); /*jshint expr: true*/ isNaN(aPart) && (aPart = 0); isNaN(bPart) && (bPart = 0); if (aPart < bPart) { return -1; } if (aPart > bPart) { return 1; } } return 0; }; YUI.Env.aliases = { "anim": ["anim-base","anim-color","anim-curve","anim-easing","anim-node-plugin","anim-scroll","anim-xy"], "anim-shape-transform": ["anim-shape"], "app": ["app-base","app-content","app-transitions","lazy-model-list","model","model-list","model-sync-rest","router","view","view-node-map"], "attribute": ["attribute-base","attribute-complex"], "attribute-events": ["attribute-observable"], "autocomplete": ["autocomplete-base","autocomplete-sources","autocomplete-list","autocomplete-plugin"], "axes": ["axis-numeric","axis-category","axis-time","axis-stacked"], "axes-base": ["axis-numeric-base","axis-category-base","axis-time-base","axis-stacked-base"], "base": ["base-base","base-pluginhost","base-build"], "cache": ["cache-base","cache-offline","cache-plugin"], "charts": ["charts-base"], "collection": ["array-extras","arraylist","arraylist-add","arraylist-filter","array-invoke"], "color": ["color-base","color-hsl","color-harmony"], "controller": ["router"], "dataschema": ["dataschema-base","dataschema-json","dataschema-xml","dataschema-array","dataschema-text"], "datasource": ["datasource-local","datasource-io","datasource-get","datasource-function","datasource-cache","datasource-jsonschema","datasource-xmlschema","datasource-arrayschema","datasource-textschema","datasource-polling"], "datatable": ["datatable-core","datatable-table","datatable-head","datatable-body","datatable-base","datatable-column-widths","datatable-message","datatable-mutable","datatable-sort","datatable-datasource"], "datatype": ["datatype-date","datatype-number","datatype-xml"], "datatype-date": ["datatype-date-parse","datatype-date-format","datatype-date-math"], "datatype-number": ["datatype-number-parse","datatype-number-format"], "datatype-xml": ["datatype-xml-parse","datatype-xml-format"], "dd": ["dd-ddm-base","dd-ddm","dd-ddm-drop","dd-drag","dd-proxy","dd-constrain","dd-drop","dd-scroll","dd-delegate"], "dom": ["dom-base","dom-screen","dom-style","selector-native","selector"], "editor": ["frame","editor-selection","exec-command","editor-base","editor-para","editor-br","editor-bidi","editor-tab","createlink-base"], "event": ["event-base","event-delegate","event-synthetic","event-mousewheel","event-mouseenter","event-key","event-focus","event-resize","event-hover","event-outside","event-touch","event-move","event-flick","event-valuechange","event-tap"], "event-custom": ["event-custom-base","event-custom-complex"], "event-gestures": ["event-flick","event-move"], "handlebars": ["handlebars-compiler"], "highlight": ["highlight-base","highlight-accentfold"], "history": ["history-base","history-hash","history-hash-ie","history-html5"], "io": ["io-base","io-xdr","io-form","io-upload-iframe","io-queue"], "json": ["json-parse","json-stringify"], "loader": ["loader-base","loader-rollup","loader-yui3"], "node": ["node-base","node-event-delegate","node-pluginhost","node-screen","node-style"], "pluginhost": ["pluginhost-base","pluginhost-config"], "querystring": ["querystring-parse","querystring-stringify"], "recordset": ["recordset-base","recordset-sort","recordset-filter","recordset-indexer"], "resize": ["resize-base","resize-proxy","resize-constrain"], "slider": ["slider-base","slider-value-range","clickable-rail","range-slider"], "template": ["template-base","template-micro"], "text": ["text-accentfold","text-wordbreak"], "widget": ["widget-base","widget-htmlparser","widget-skin","widget-uievents"] }; }, '@VERSION@', {"use": ["get", "features", "intl-base", "yui-log", "yui-later"]}); YUI.add('get', function (Y, NAME) { /*jslint boss:true, expr:true, laxbreak: true */ /** Provides dynamic loading of remote JavaScript and CSS resources. @module get @class Get @static **/ var Lang = Y.Lang, CUSTOM_ATTRS, // defined lazily in Y.Get.Transaction._createNode() Get, Transaction; Y.Get = Get = { // -- Public Properties ---------------------------------------------------- /** Default options for CSS requests. Options specified here will override global defaults for CSS requests. See the `options` property for all available options. @property cssOptions @type Object @static @since 3.5.0 **/ cssOptions: { attributes: { rel: 'stylesheet' }, doc : Y.config.linkDoc || Y.config.doc, pollInterval: 50 }, /** Default options for JS requests. Options specified here will override global defaults for JS requests. See the `options` property for all available options. @property jsOptions @type Object @static @since 3.5.0 **/ jsOptions: { autopurge: true, doc : Y.config.scriptDoc || Y.config.doc }, /** Default options to use for all requests. Note that while all available options are documented here for ease of discovery, some options (like callback functions) only make sense at the transaction level. Callback functions specified via the options object or the `options` parameter of the `css()`, `js()`, or `load()` methods will receive the transaction object as a parameter. See `Y.Get.Transaction` for details on the properties and methods available on transactions. @static @since 3.5.0 @property {Object} options @property {Boolean} [options.async=false] Whether or not to load scripts asynchronously, meaning they're requested in parallel and execution order is not guaranteed. Has no effect on CSS, since CSS is always loaded asynchronously. @property {Object} [options.attributes] HTML attribute name/value pairs that should be added to inserted nodes. By default, the `charset` attribute will be set to "utf-8" and nodes will be given an auto-generated `id` attribute, but you can override these with your own values if desired. @property {Boolean} [options.autopurge] Whether or not to automatically purge inserted nodes after the purge threshold is reached. This is `true` by default for JavaScript, but `false` for CSS since purging a CSS node will also remove any styling applied by the referenced file. @property {Object} [options.context] `this` object to use when calling callback functions. Defaults to the transaction object. @property {Mixed} [options.data] Arbitrary data object to pass to "on*" callbacks. @property {Document} [options.doc] Document into which nodes should be inserted. By default, the current document is used. @property {HTMLElement|String} [options.insertBefore] HTML element or id string of an element before which all generated nodes should be inserted. If not specified, Get will automatically determine the best place to insert nodes for maximum compatibility. @property {Function} [options.onEnd] Callback to execute after a transaction is complete, regardless of whether it succeeded or failed. @property {Function} [options.onFailure] Callback to execute after a transaction fails, times out, or is aborted. @property {Function} [options.onProgress] Callback to execute after each individual request in a transaction either succeeds or fails. @property {Function} [options.onSuccess] Callback to execute after a transaction completes successfully with no errors. Note that in browsers that don't support the `error` event on CSS `<link>` nodes, a failed CSS request may still be reported as a success because in these browsers it can be difficult or impossible to distinguish between success and failure for CSS resources. @property {Function} [options.onTimeout] Callback to execute after a transaction times out. @property {Number} [options.pollInterval=50] Polling interval (in milliseconds) for detecting CSS load completion in browsers that don't support the `load` event on `<link>` nodes. This isn't used for JavaScript. @property {Number} [options.purgethreshold=20] Number of nodes to insert before triggering an automatic purge when `autopurge` is `true`. @property {Number} [options.timeout] Number of milliseconds to wait before aborting a transaction. When a timeout occurs, the `onTimeout` callback is called, followed by `onFailure` and finally `onEnd`. By default, there is no timeout. @property {String} [options.type] Resource type ("css" or "js"). This option is set automatically by the `css()` and `js()` functions and will be ignored there, but may be useful when using the `load()` function. If not specified, the type will be inferred from the URL, defaulting to "js" if the URL doesn't contain a recognizable file extension. **/ options: { attributes: { charset: 'utf-8' }, purgethreshold: 20 }, // -- Protected Properties ------------------------------------------------- /** Regex that matches a CSS URL. Used to guess the file type when it's not specified. @property REGEX_CSS @type RegExp @final @protected @static @since 3.5.0 **/ REGEX_CSS: /\.css(?:[?;].*)?$/i, /** Regex that matches a JS URL. Used to guess the file type when it's not specified. @property REGEX_JS @type RegExp @final @protected @static @since 3.5.0 **/ REGEX_JS : /\.js(?:[?;].*)?$/i, /** Contains information about the current environment, such as what script and link injection features it supports. This object is created and populated the first time the `_getEnv()` method is called. @property _env @type Object @protected @static @since 3.5.0 **/ /** Mapping of document _yuid strings to <head> or <base> node references so we don't have to look the node up each time we want to insert a request node. @property _insertCache @type Object @protected @static @since 3.5.0 **/ _insertCache: {}, /** Information about the currently pending transaction, if any. This is actually an object with two properties: `callback`, containing the optional callback passed to `css()`, `load()`, or `js()`; and `transaction`, containing the actual transaction instance. @property _pending @type Object @protected @static @since 3.5.0 **/ _pending: null, /** HTML nodes eligible to be purged next time autopurge is triggered. @property _purgeNodes @type HTMLElement[] @protected @static @since 3.5.0 **/ _purgeNodes: [], /** Queued transactions and associated callbacks. @property _queue @type Object[] @protected @static @since 3.5.0 **/ _queue: [], // -- Public Methods ------------------------------------------------------- /** Aborts the specified transaction. This will cause the transaction's `onFailure` callback to be called and will prevent any new script and link nodes from being added to the document, but any resources that have already been requested will continue loading (there's no safe way to prevent this, unfortunately). *Note:* This method is deprecated as of 3.5.0, and will be removed in a future version of YUI. Use the transaction-level `abort()` method instead. @method abort @param {Get.Transaction} transaction Transaction to abort. @deprecated Use the `abort()` method on the transaction instead. @static **/ abort: function (transaction) { var i, id, item, len, pending; if (!transaction.abort) { id = transaction; pending = this._pending; transaction = null; if (pending && pending.transaction.id === id) { transaction = pending.transaction; this._pending = null; } else { for (i = 0, len = this._queue.length; i < len; ++i) { item = this._queue[i].transaction; if (item.id === id) { transaction = item; this._queue.splice(i, 1); break; } } } } transaction && transaction.abort(); }, /** Loads one or more CSS files. The _urls_ parameter may be provided as a URL string, a request object, or an array of URL strings and/or request objects. A request object is just an object that contains a `url` property and zero or more options that should apply specifically to that request. Request-specific options take priority over transaction-level options and default options. URLs may be relative or absolute, and do not have to have the same origin as the current page. The `options` parameter may be omitted completely and a callback passed in its place, if desired. @example // Load a single CSS file and log a message on completion. Y.Get.css('foo.css', function (err) { if (err) { } else { } }); // Load multiple CSS files and log a message when all have finished // loading. var urls = ['foo.css', 'http://example.com/bar.css', 'baz/quux.css']; Y.Get.css(urls, function (err) { if (err) { } else { } }); // Specify transaction-level options, which will apply to all requests // within the transaction. Y.Get.css(urls, { attributes: {'class': 'my-css'}, timeout : 5000 }); // Specify per-request options, which override transaction-level and // default options. Y.Get.css([ {url: 'foo.css', attributes: {id: 'foo'}}, {url: 'bar.css', attributes: {id: 'bar', charset: 'iso-8859-1'}} ]); @method css @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} callback.err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} callback.transaction Transaction object. @return {Get.Transaction} Transaction object. @static **/ css: function (urls, options, callback) { return this._load('css', urls, options, callback); }, /** Loads one or more JavaScript resources. The _urls_ parameter may be provided as a URL string, a request object, or an array of URL strings and/or request objects. A request object is just an object that contains a `url` property and zero or more options that should apply specifically to that request. Request-specific options take priority over transaction-level options and default options. URLs may be relative or absolute, and do not have to have the same origin as the current page. The `options` parameter may be omitted completely and a callback passed in its place, if desired. Scripts will be executed in the order they're specified unless the `async` option is `true`, in which case they'll be loaded in parallel and executed in whatever order they finish loading. @example // Load a single JS file and log a message on completion. Y.Get.js('foo.js', function (err) { if (err) { } else { } }); // Load multiple JS files, execute them in order, and log a message when // all have finished loading. var urls = ['foo.js', 'http://example.com/bar.js', 'baz/quux.js']; Y.Get.js(urls, function (err) { if (err) { } else { } }); // Specify transaction-level options, which will apply to all requests // within the transaction. Y.Get.js(urls, { attributes: {'class': 'my-js'}, timeout : 5000 }); // Specify per-request options, which override transaction-level and // default options. Y.Get.js([ {url: 'foo.js', attributes: {id: 'foo'}}, {url: 'bar.js', attributes: {id: 'bar', charset: 'iso-8859-1'}} ]); @method js @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} callback.err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} callback.transaction Transaction object. @return {Get.Transaction} Transaction object. @since 3.5.0 @static **/ js: function (urls, options, callback) { return this._load('js', urls, options, callback); }, /** Loads one or more CSS and/or JavaScript resources in the same transaction. Use this method when you want to load both CSS and JavaScript in a single transaction and be notified when all requested URLs have finished loading, regardless of type. Behavior and options are the same as for the `css()` and `js()` methods. If a resource type isn't specified in per-request options or transaction-level options, Get will guess the file type based on the URL's extension (`.css` or `.js`, with or without a following query string). If the file type can't be guessed from the URL, a warning will be logged and Get will assume the URL is a JavaScript resource. @example // Load both CSS and JS files in a single transaction, and log a message // when all files have finished loading. Y.Get.load(['foo.css', 'bar.js', 'baz.css'], function (err) { if (err) { } else { } }); @method load @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} Transaction object. @return {Get.Transaction} Transaction object. @since 3.5.0 @static **/ load: function (urls, options, callback) { return this._load(null, urls, options, callback); }, // -- Protected Methods ---------------------------------------------------- /** Triggers an automatic purge if the purge threshold has been reached. @method _autoPurge @param {Number} threshold Purge threshold to use, in milliseconds. @protected @since 3.5.0 @static **/ _autoPurge: function (threshold) { if (threshold && this._purgeNodes.length >= threshold) { this._purge(this._purgeNodes); } }, /** Populates the `_env` property with information about the current environment. @method _getEnv @return {Object} Environment information. @protected @since 3.5.0 @static **/ _getEnv: function () { var doc = Y.config.doc, ua = Y.UA; // Note: some of these checks require browser sniffs since it's not // feasible to load test files on every pageview just to perform a // feature test. I'm sorry if this makes you sad. return (this._env = { // True if this is a browser that supports disabling async mode on // dynamically created script nodes. See // https://developer.mozilla.org/En/HTML/Element/Script#Attributes // IE10 doesn't return true for the MDN feature test, so setting it explicitly, // because it is async by default, and allows you to disable async by setting it to false async: (doc && doc.createElement('script').async === true) || (ua.ie >= 10), // True if this browser fires an event when a dynamically injected // link node fails to load. This is currently true for Firefox 9+ // and WebKit 535.24+ cssFail: ua.gecko >= 9 || ua.compareVersions(ua.webkit, 535.24) >= 0, // True if this browser fires an event when a dynamically injected // link node finishes loading. This is currently true for IE, Opera, // Firefox 9+, and WebKit 535.24+. Note that IE versions <9 fire the // DOM 0 "onload" event, but not "load". All versions of IE fire // "onload". // davglass: Seems that Chrome on Android needs this to be false. cssLoad: ( (!ua.gecko && !ua.webkit) || ua.gecko >= 9 || ua.compareVersions(ua.webkit, 535.24) >= 0 ) && !(ua.chrome && ua.chrome <= 18), // True if this browser preserves script execution order while // loading scripts in parallel as long as the script node's `async` // attribute is set to false to explicitly disable async execution. preservesScriptOrder: !!(ua.gecko || ua.opera || (ua.ie && ua.ie >= 10)) }); }, _getTransaction: function (urls, options) { var requests = [], i, len, req, url; if (!Lang.isArray(urls)) { urls = [urls]; } options = Y.merge(this.options, options); // Clone the attributes object so we don't end up modifying it by ref. options.attributes = Y.merge(this.options.attributes, options.attributes); for (i = 0, len = urls.length; i < len; ++i) { url = urls[i]; req = {attributes: {}}; // If `url` is a string, we create a URL object for it, then mix in // global options and request-specific options. If it's an object // with a "url" property, we assume it's a request object containing // URL-specific options. if (typeof url === 'string') { req.url = url; } else if (url.url) { // URL-specific options override both global defaults and // request-specific options. Y.mix(req, url, false, null, 0, true); url = url.url; // Make url a string so we can use it later. } else { continue; } Y.mix(req, options, false, null, 0, true); // If we didn't get an explicit type for this URL either in the // request options or the URL-specific options, try to determine // one from the file extension. if (!req.type) { if (this.REGEX_CSS.test(url)) { req.type = 'css'; } else { if (!this.REGEX_JS.test(url)) { } req.type = 'js'; } } // Mix in type-specific default options, but don't overwrite any // options that have already been set. Y.mix(req, req.type === 'js' ? this.jsOptions : this.cssOptions, false, null, 0, true); // Give the node an id attribute if it doesn't already have one. req.attributes.id || (req.attributes.id = Y.guid()); // Backcompat for <3.5.0 behavior. if (req.win) { req.doc = req.win.document; } else { req.win = req.doc.defaultView || req.doc.parentWindow; } if (req.charset) { req.attributes.charset = req.charset; } requests.push(req); } return new Transaction(requests, options); }, _load: function (type, urls, options, callback) { var transaction; // Allow callback as third param. if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); options.type = type; options._onFinish = Get._onTransactionFinish; if (!this._env) { this._getEnv(); } transaction = this._getTransaction(urls, options); this._queue.push({ callback : callback, transaction: transaction }); this._next(); return transaction; }, _onTransactionFinish : function() { Get._pending = null; Get._next(); }, _next: function () { var item; if (this._pending) { return; } item = this._queue.shift(); if (item) { this._pending = item; item.transaction.execute(item.callback); } }, _purge: function (nodes) { var purgeNodes = this._purgeNodes, isTransaction = nodes !== purgeNodes, index, node; while (node = nodes.pop()) { // assignment // Don't purge nodes that haven't finished loading (or errored out), // since this can hang the transaction. if (!node._yuiget_finished) { continue; } node.parentNode && node.parentNode.removeChild(node); // If this is a transaction-level purge and this node also exists in // the Get-level _purgeNodes array, we need to remove it from // _purgeNodes to avoid creating a memory leak. The indexOf lookup // sucks, but until we get WeakMaps, this is the least troublesome // way to do this (we can't just hold onto node ids because they may // not be in the same document). if (isTransaction) { index = Y.Array.indexOf(purgeNodes, node); if (index > -1) { purgeNodes.splice(index, 1); } } } } }; /** Alias for `js()`. @method script @static **/ Get.script = Get.js; /** Represents a Get transaction, which may contain requests for one or more JS or CSS files. This class should not be instantiated manually. Instances will be created and returned as needed by Y.Get's `css()`, `js()`, and `load()` methods. @class Get.Transaction @constructor @since 3.5.0 **/ Get.Transaction = Transaction = function (requests, options) { var self = this; self.id = Transaction._lastId += 1; self.data = options.data; self.errors = []; self.nodes = []; self.options = options; self.requests = requests; self._callbacks = []; // callbacks to call after execution finishes self._queue = []; self._reqsWaiting = 0; // Deprecated pre-3.5.0 properties. self.tId = self.id; // Use `id` instead. self.win = options.win || Y.config.win; }; /** Arbitrary data object associated with this transaction. This object comes from the options passed to `Get.css()`, `Get.js()`, or `Get.load()`, and will be `undefined` if no data object was specified. @property {Object} data **/ /** Array of errors that have occurred during this transaction, if any. @since 3.5.0 @property {Object[]} errors @property {String} errors.error Error message. @property {Object} errors.request Request object related to the error. **/ /** Numeric id for this transaction, unique among all transactions within the same YUI sandbox in the current pageview. @property {Number} id @since 3.5.0 **/ /** HTMLElement nodes (native ones, not YUI Node instances) that have been inserted during the current transaction. @property {HTMLElement[]} nodes **/ /** Options associated with this transaction. See `Get.options` for the full list of available options. @property {Object} options @since 3.5.0 **/ /** Request objects contained in this transaction. Each request object represents one CSS or JS URL that will be (or has been) requested and loaded into the page. @property {Object} requests @since 3.5.0 **/ /** Id of the most recent transaction. @property _lastId @type Number @protected @static **/ Transaction._lastId = 0; Transaction.prototype = { // -- Public Properties ---------------------------------------------------- /** Current state of this transaction. One of "new", "executing", or "done". @property _state @type String @protected **/ _state: 'new', // "new", "executing", or "done" // -- Public Methods ------------------------------------------------------- /** Aborts this transaction. This will cause the transaction's `onFailure` callback to be called and will prevent any new script and link nodes from being added to the document, but any resources that have already been requested will continue loading (there's no safe way to prevent this, unfortunately). @method abort @param {String} [msg="Aborted."] Optional message to use in the `errors` array describing why the transaction was aborted. **/ abort: function (msg) { this._pending = null; this._pendingCSS = null; this._pollTimer = clearTimeout(this._pollTimer); this._queue = []; this._reqsWaiting = 0; this.errors.push({error: msg || 'Aborted'}); this._finish(); }, /** Begins execting the transaction. There's usually no reason to call this manually, since Get will call it automatically when other pending transactions have finished. If you really want to execute your transaction before Get does, you can, but be aware that this transaction's scripts may end up executing before the scripts in other pending transactions. If the transaction is already executing, the specified callback (if any) will be queued and called after execution finishes. If the transaction has already finished, the callback will be called immediately (the transaction will not be executed again). @method execute @param {Function} callback Callback function to execute after all requests in the transaction are complete, or after the transaction is aborted. **/ execute: function (callback) { var self = this, requests = self.requests, state = self._state, i, len, queue, req; if (state === 'done') { callback && callback(self.errors.length ? self.errors : null, self); return; } else { callback && self._callbacks.push(callback); if (state === 'executing') { return; } } self._state = 'executing'; self._queue = queue = []; if (self.options.timeout) { self._timeout = setTimeout(function () { self.abort('Timeout'); }, self.options.timeout); } self._reqsWaiting = requests.length; for (i = 0, len = requests.length; i < len; ++i) { req = requests[i]; if (req.async || req.type === 'css') { // No need to queue CSS or fully async JS. self._insert(req); } else { queue.push(req); } } self._next(); }, /** Manually purges any `<script>` or `<link>` nodes this transaction has created. Be careful when purging a transaction that contains CSS requests, since removing `<link>` nodes will also remove any styles they applied. @method purge **/ purge: function () { Get._purge(this.nodes); }, // -- Protected Methods ---------------------------------------------------- _createNode: function (name, attrs, doc) { var node = doc.createElement(name), attr, testEl; if (!CUSTOM_ATTRS) { // IE6 and IE7 expect property names rather than attribute names for // certain attributes. Rather than sniffing, we do a quick feature // test the first time _createNode() runs to determine whether we // need to provide a workaround. testEl = doc.createElement('div'); testEl.setAttribute('class', 'a'); CUSTOM_ATTRS = testEl.className === 'a' ? {} : { 'for' : 'htmlFor', 'class': 'className' }; } for (attr in attrs) { if (attrs.hasOwnProperty(attr)) { node.setAttribute(CUSTOM_ATTRS[attr] || attr, attrs[attr]); } } return node; }, _finish: function () { var errors = this.errors.length ? this.errors : null, options = this.options, thisObj = options.context || this, data, i, len; if (this._state === 'done') { return; } this._state = 'done'; for (i = 0, len = this._callbacks.length; i < len; ++i) { this._callbacks[i].call(thisObj, errors, this); } data = this._getEventData(); if (errors) { if (options.onTimeout && errors[errors.length - 1].error === 'Timeout') { options.onTimeout.call(thisObj, data); } if (options.onFailure) { options.onFailure.call(thisObj, data); } } else if (options.onSuccess) { options.onSuccess.call(thisObj, data); } if (options.onEnd) { options.onEnd.call(thisObj, data); } if (options._onFinish) { options._onFinish(); } }, _getEventData: function (req) { if (req) { // This merge is necessary for backcompat. I hate it. return Y.merge(this, { abort : this.abort, // have to copy these because the prototype isn't preserved purge : this.purge, request: req, url : req.url, win : req.win }); } else { return this; } }, _getInsertBefore: function (req) { var doc = req.doc, el = req.insertBefore, cache, docStamp; if (el) { return typeof el === 'string' ? doc.getElementById(el) : el; } cache = Get._insertCache; docStamp = Y.stamp(doc); if ((el = cache[docStamp])) { // assignment return el; } // Inserting before a <base> tag apparently works around an IE bug // (according to a comment from pre-3.5.0 Y.Get), but I'm not sure what // bug that is, exactly. Better safe than sorry? if ((el = doc.getElementsByTagName('base')[0])) { // assignment return (cache[docStamp] = el); } // Look for a <head> element. el = doc.head || doc.getElementsByTagName('head')[0]; if (el) { // Create a marker node at the end of <head> to use as an insertion // point. Inserting before this node will ensure that all our CSS // gets inserted in the correct order, to maintain style precedence. el.appendChild(doc.createTextNode('')); return (cache[docStamp] = el.lastChild); } // If all else fails, just insert before the first script node on the // page, which is virtually guaranteed to exist. return (cache[docStamp] = doc.getElementsByTagName('script')[0]); }, _insert: function (req) { var env = Get._env, insertBefore = this._getInsertBefore(req), isScript = req.type === 'js', node = req.node, self = this, ua = Y.UA, cssTimeout, nodeType; if (!node) { if (isScript) { nodeType = 'script'; } else if (!env.cssLoad && ua.gecko) { nodeType = 'style'; } else { nodeType = 'link'; } node = req.node = this._createNode(nodeType, req.attributes, req.doc); } function onError() { self._progress('Failed to load ' + req.url, req); } function onLoad() { if (cssTimeout) { clearTimeout(cssTimeout); } self._progress(null, req); } // Deal with script asynchronicity. if (isScript) { node.setAttribute('src', req.url); if (req.async) { // Explicitly indicate that we want the browser to execute this // script asynchronously. This is necessary for older browsers // like Firefox <4. node.async = true; } else { if (env.async) { // This browser treats injected scripts as async by default // (standard HTML5 behavior) but asynchronous loading isn't // desired, so tell the browser not to mark this script as // async. node.async = false; } // If this browser doesn't preserve script execution order based // on insertion order, we'll need to avoid inserting other // scripts until this one finishes loading. if (!env.preservesScriptOrder) { this._pending = req; } } } else { if (!env.cssLoad && ua.gecko) { // In Firefox <9, we can import the requested URL into a <style> // node and poll for the existence of node.sheet.cssRules. This // gives us a reliable way to determine CSS load completion that // also works for cross-domain stylesheets. // // Props to Zach Leatherman for calling my attention to this // technique. node.innerHTML = (req.attributes.charset ? '@charset "' + req.attributes.charset + '";' : '') + '@import "' + req.url + '";'; } else { node.setAttribute('href', req.url); } } // Inject the node. if (isScript && ua.ie && (ua.ie < 9 || (document.documentMode && document.documentMode < 9))) { // Script on IE < 9, and IE 9+ when in IE 8 or older modes, including quirks mode. node.onreadystatechange = function () { if (/loaded|complete/.test(node.readyState)) { node.onreadystatechange = null; onLoad(); } }; } else if (!isScript && !env.cssLoad) { // CSS on Firefox <9 or WebKit. this._poll(req); } else { // Script or CSS on everything else. Using DOM 0 events because that // evens the playing field with older IEs. if (ua.ie >= 10) { // We currently need to introduce a timeout for IE10, since it // calls onerror/onload synchronously for 304s - messing up existing // program flow. // Remove this block if the following bug gets fixed by GA /*jshint maxlen: 1500 */ // https://connect.microsoft.com/IE/feedback/details/763871/dynamically-loaded-scripts-with-304s-responses-interrupt-the-currently-executing-js-thread-onload node.onerror = function() { setTimeout(onError, 0); }; node.onload = function() { setTimeout(onLoad, 0); }; } else { node.onerror = onError; node.onload = onLoad; } // If this browser doesn't fire an event when CSS fails to load, // fail after a timeout to avoid blocking the transaction queue. if (!env.cssFail && !isScript) { cssTimeout = setTimeout(onError, req.timeout || 3000); } } this.nodes.push(node); insertBefore.parentNode.insertBefore(node, insertBefore); }, _next: function () { if (this._pending) { return; } // If there are requests in the queue, insert the next queued request. // Otherwise, if we're waiting on already-inserted requests to finish, // wait longer. If there are no queued requests and we're not waiting // for anything to load, then we're done! if (this._queue.length) { this._insert(this._queue.shift()); } else if (!this._reqsWaiting) { this._finish(); } }, _poll: function (newReq) { var self = this, pendingCSS = self._pendingCSS, isWebKit = Y.UA.webkit, i, hasRules, j, nodeHref, req, sheets; if (newReq) { pendingCSS || (pendingCSS = self._pendingCSS = []); pendingCSS.push(newReq); if (self._pollTimer) { // A poll timeout is already pending, so no need to create a // new one. return; } } self._pollTimer = null; // Note: in both the WebKit and Gecko hacks below, a CSS URL that 404s // will still be treated as a success. There's no good workaround for // this. for (i = 0; i < pendingCSS.length; ++i) { req = pendingCSS[i]; if (isWebKit) { // Look for a stylesheet matching the pending URL. sheets = req.doc.styleSheets; j = sheets.length; nodeHref = req.node.href; while (--j >= 0) { if (sheets[j].href === nodeHref) { pendingCSS.splice(i, 1); i -= 1; self._progress(null, req); break; } } } else { // Many thanks to Zach Leatherman for calling my attention to // the @import-based cross-domain technique used here, and to // Oleg Slobodskoi for an earlier same-domain implementation. // // See Zach's blog for more details: // http://www.zachleat.com/web/2010/07/29/load-css-dynamically/ try { // We don't really need to store this value since we never // use it again, but if we don't store it, Closure Compiler // assumes the code is useless and removes it. hasRules = !!req.node.sheet.cssRules; // If we get here, the stylesheet has loaded. pendingCSS.splice(i, 1); i -= 1; self._progress(null, req); } catch (ex) { // An exception means the stylesheet is still loading. } } } if (pendingCSS.length) { self._pollTimer = setTimeout(function () { self._poll.call(self); }, self.options.pollInterval); } }, _progress: function (err, req) { var options = this.options; if (err) { req.error = err; this.errors.push({ error : err, request: req }); } req.node._yuiget_finished = req.finished = true; if (options.onProgress) { options.onProgress.call(options.context || this, this._getEventData(req)); } if (req.autopurge) { // Pre-3.5.0 Get always excludes the most recent node from an // autopurge. I find this odd, but I'm keeping that behavior for // the sake of backcompat. Get._autoPurge(this.options.purgethreshold); Get._purgeNodes.push(req.node); } if (this._pending === req) { this._pending = null; } this._reqsWaiting -= 1; this._next(); } }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('features', function (Y, NAME) { var feature_tests = {}; /** Contains the core of YUI's feature test architecture. @module features */ /** * Feature detection * @class Features * @static */ Y.mix(Y.namespace('Features'), { /** * Object hash of all registered feature tests * @property tests * @type Object */ tests: feature_tests, /** * Add a test to the system * * ``` * Y.Features.add("load", "1", {}); * ``` * * @method add * @param {String} cat The category, right now only 'load' is supported * @param {String} name The number sequence of the test, how it's reported in the URL or config: 1, 2, 3 * @param {Object} o Object containing test properties * @param {String} o.name The name of the test * @param {Function} o.test The test function to execute, the only argument to the function is the `Y` instance * @param {String} o.trigger The module that triggers this test. */ add: function(cat, name, o) { feature_tests[cat] = feature_tests[cat] || {}; feature_tests[cat][name] = o; }, /** * Execute all tests of a given category and return the serialized results * * ``` * caps=1:1;2:1;3:0 * ``` * @method all * @param {String} cat The category to execute * @param {Array} args The arguments to pass to the test function * @return {String} A semi-colon separated string of tests and their success/failure: 1:1;2:1;3:0 */ all: function(cat, args) { var cat_o = feature_tests[cat], // results = {}; result = []; if (cat_o) { Y.Object.each(cat_o, function(v, k) { result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0)); }); } return (result.length) ? result.join(';') : ''; }, /** * Run a sepecific test and return a Boolean response. * * ``` * Y.Features.test("load", "1"); * ``` * * @method test * @param {String} cat The category of the test to run * @param {String} name The name of the test to run * @param {Array} args The arguments to pass to the test function * @return {Boolean} True or false if the test passed/failed. */ test: function(cat, name, args) { args = args || []; var result, ua, test, cat_o = feature_tests[cat], feature = cat_o && cat_o[name]; if (!feature) { } else { result = feature.result; if (Y.Lang.isUndefined(result)) { ua = feature.ua; if (ua) { result = (Y.UA[ua]); } test = feature.test; if (test && ((!ua) || result)) { result = test.apply(Y, args); } feature.result = result; } } return result; } }); // Y.Features.add("load", "1", {}); // Y.Features.test("load", "1"); // caps=1:1;2:0;3:1; /* This file is auto-generated by (yogi loader --yes --mix --start ../) */ /*jshint maxlen:900, eqeqeq: false */ var add = Y.Features.add; // app-transitions-native add('load', '0', { "name": "app-transitions-native", "test": function (Y) { var doc = Y.config.doc, node = doc ? doc.documentElement : null; if (node && node.style) { return ('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return false; }, "trigger": "app-transitions" }); // autocomplete-list-keys add('load', '1', { "name": "autocomplete-list-keys", "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }); // dd-gestures add('load', '2', { "name": "dd-gestures", "trigger": "dd-drag", "ua": "touchEnabled" }); // dom-style-ie add('load', '3', { "name": "dom-style-ie", "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }); // editor-para-ie add('load', '4', { "name": "editor-para-ie", "trigger": "editor-para", "ua": "ie", "when": "instead" }); // event-base-ie add('load', '5', { "name": "event-base-ie", "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }); // graphics-canvas add('load', '6', { "name": "graphics-canvas", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-canvas-default add('load', '7', { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-svg add('load', '8', { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-svg-default add('load', '9', { "name": "graphics-svg-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-vml add('load', '10', { "name": "graphics-vml", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // graphics-vml-default add('load', '11', { "name": "graphics-vml-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // history-hash-ie add('load', '12', { "name": "history-hash-ie", "test": function (Y) { var docMode = Y.config.doc && Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }); // io-nodejs add('load', '13', { "name": "io-nodejs", "trigger": "io-base", "ua": "nodejs" }); // json-parse-shim add('load', '14', { "name": "json-parse-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONParse !== false && !!Native; function workingNative( k, v ) { return k === "ok" ? true : v; } // Double check basic functionality. This is mainly to catch early broken // implementations of the JSON API in Firefox 3.1 beta1 and beta2 if ( nativeSupport ) { try { nativeSupport = ( Native.parse( '{"ok":false}', workingNative ) ).ok; } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-parse" }); // json-stringify-shim add('load', '15', { "name": "json-stringify-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONStringify !== false && !!Native; // Double check basic native functionality. This is primarily to catch broken // early JSON API implementations in Firefox 3.1 beta1 and beta2. if ( nativeSupport ) { try { nativeSupport = ( '0' === Native.stringify(0) ); } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-stringify" }); // scrollview-base-ie add('load', '16', { "name": "scrollview-base-ie", "trigger": "scrollview-base", "ua": "ie" }); // selector-css2 add('load', '17', { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }); // transition-timer add('load', '18', { "name": "transition-timer", "test": function (Y) { var DOCUMENT = Y.config.doc, node = (DOCUMENT) ? DOCUMENT.documentElement: null, ret = true; if (node && node.style) { ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return ret; }, "trigger": "transition" }); // widget-base-ie add('load', '19', { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }); // yql-jsonp add('load', '20', { "name": "yql-jsonp", "test": function (Y) { /* Only load the JSONP module when not in nodejs or winjs TODO Make the winjs module a CORS module */ return (!Y.UA.nodejs && !Y.UA.winjs); }, "trigger": "yql", "when": "after" }); // yql-nodejs add('load', '21', { "name": "yql-nodejs", "trigger": "yql", "ua": "nodejs", "when": "after" }); // yql-winjs add('load', '22', { "name": "yql-winjs", "trigger": "yql", "ua": "winjs", "when": "after" }); }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('intl-base', function (Y, NAME) { /** * The Intl utility provides a central location for managing sets of * localized resources (strings and formatting patterns). * * @class Intl * @uses EventTarget * @static */ var SPLIT_REGEX = /[, ]/; Y.mix(Y.namespace('Intl'), { /** * Returns the language among those available that * best matches the preferred language list, using the Lookup * algorithm of BCP 47. * If none of the available languages meets the user's preferences, * then "" is returned. * Extended language ranges are not supported. * * @method lookupBestLang * @param {String[] | String} preferredLanguages The list of preferred * languages in descending preference order, represented as BCP 47 * language tags. A string array or a comma-separated list. * @param {String[]} availableLanguages The list of languages * that the application supports, represented as BCP 47 language * tags. * * @return {String} The available language that best matches the * preferred language list, or "". * @since 3.1.0 */ lookupBestLang: function(preferredLanguages, availableLanguages) { var i, language, result, index; // check whether the list of available languages contains language; // if so return it function scan(language) { var i; for (i = 0; i < availableLanguages.length; i += 1) { if (language.toLowerCase() === availableLanguages[i].toLowerCase()) { return availableLanguages[i]; } } } if (Y.Lang.isString(preferredLanguages)) { preferredLanguages = preferredLanguages.split(SPLIT_REGEX); } for (i = 0; i < preferredLanguages.length; i += 1) { language = preferredLanguages[i]; if (!language || language === '*') { continue; } // check the fallback sequence for one language while (language.length > 0) { result = scan(language); if (result) { return result; } else { index = language.lastIndexOf('-'); if (index >= 0) { language = language.substring(0, index); // one-character subtags get cut along with the // following subtag if (index >= 2 && language.charAt(index - 2) === '-') { language = language.substring(0, index - 2); } } else { // nothing available for this language break; } } } } return ''; } }); }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('yui-log', function (Y, NAME) { /** * Provides console log capability and exposes a custom event for * console implementations. This module is a `core` YUI module, * <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-log */ var INSTANCE = Y, LOGEVENT = 'yui:log', UNDEFINED = 'undefined', LEVELS = { debug: 1, info: 2, warn: 4, error: 8 }; /** * If the 'debug' config is true, a 'yui:log' event will be * dispatched, which the Console widget and anything else * can consume. If the 'useBrowserConsole' config is true, it will * write to the browser console if available. YUI-specific log * messages will only be present in the -debug versions of the * JS files. The build system is supposed to remove log statements * from the raw and minified versions of the files. * * @method log * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.log = function(msg, cat, src, silent) { var bail, excl, incl, m, f, minlevel, Y = INSTANCE, c = Y.config, publisher = (Y.fire) ? Y : YUI.Env.globalEvents; // suppress log message if the config is off or the event stack // or the event call stack contains a consumer of the yui:log event if (c.debug) { // apply source filters src = src || ""; if (typeof src !== "undefined") { excl = c.logExclude; incl = c.logInclude; if (incl && !(src in incl)) { bail = 1; } else if (incl && (src in incl)) { bail = !incl[src]; } else if (excl && (src in excl)) { bail = excl[src]; } // Determine the current minlevel as defined in configuration Y.config.logLevel = Y.config.logLevel || 'debug'; minlevel = LEVELS[Y.config.logLevel.toLowerCase()]; if (cat in LEVELS && LEVELS[cat] < minlevel) { // Skip this message if the we don't meet the defined minlevel bail = 1; } } if (!bail) { if (c.useBrowserConsole) { m = (src) ? src + ': ' + msg : msg; if (Y.Lang.isFunction(c.logFn)) { c.logFn.call(Y, msg, cat, src); } else if (typeof console !== UNDEFINED && console.log) { f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log'; console[f](m); } else if (typeof opera !== UNDEFINED) { opera.postError(m); } } if (publisher && !silent) { if (publisher === Y && (!publisher.getEvent(LOGEVENT))) { publisher.publish(LOGEVENT, { broadcast: 2 }); } publisher.fire(LOGEVENT, { msg: msg, cat: cat, src: src }); } } } return Y; }; /** * Write a system message. This message will be preserved in the * minified and raw versions of the YUI files, unlike log statements. * @method message * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.message = function() { return INSTANCE.log.apply(INSTANCE, arguments); }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('yui-later', function (Y, NAME) { /** * Provides a setTimeout/setInterval wrapper. This module is a `core` YUI module, * <a href="../classes/YUI.html#method_later">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-later */ var NO_ARGS = []; /** * Executes the supplied function in the context of the supplied * object 'when' milliseconds later. Executes the function a * single time unless periodic is set to true. * @for YUI * @method later * @param when {int} the number of milliseconds to wait until the fn * is executed. * @param o the context object. * @param fn {Function|String} the function to execute or the name of * the method in the 'o' object to execute. * @param data [Array] data that is provided to the function. This * accepts either a single item or an array. If an array is provided, * the function is executed with one parameter for each array item. * If you need to pass a single array parameter, it needs to be wrapped * in an array [myarray]. * * Note: native methods in IE may not have the call and apply methods. * In this case, it will work, but you are limited to four arguments. * * @param periodic {boolean} if true, executes continuously at supplied * interval until canceled. * @return {object} a timer object. Call the cancel() method on this * object to stop the timer. */ Y.later = function(when, o, fn, data, periodic) { when = when || 0; data = (!Y.Lang.isUndefined(data)) ? Y.Array(data) : NO_ARGS; o = o || Y.config.win || Y; var cancelled = false, method = (o && Y.Lang.isString(fn)) ? o[fn] : fn, wrapper = function() { // IE 8- may execute a setInterval callback one last time // after clearInterval was called, so in order to preserve // the cancel() === no more runny-run, we have to jump through // an extra hoop. if (!cancelled) { if (!method.apply) { method(data[0], data[1], data[2], data[3]); } else { method.apply(o, data || NO_ARGS); } } }, id = (periodic) ? setInterval(wrapper, when) : setTimeout(wrapper, when); return { id: id, interval: periodic, cancel: function() { cancelled = true; if (this.interval) { clearInterval(id); } else { clearTimeout(id); } } }; }; Y.Lang.later = Y.later; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('yui', function (Y, NAME) {}, '@VERSION@', {"use": ["get", "features", "intl-base", "yui-log", "yui-later"]}); YUI.add('oop', function (Y, NAME) { /** Adds object inheritance and manipulation utilities to the YUI instance. This module is required by most YUI components. @module oop **/ var L = Y.Lang, A = Y.Array, OP = Object.prototype, CLONE_MARKER = '_~yuim~_', hasOwn = OP.hasOwnProperty, toString = OP.toString; function dispatch(o, f, c, proto, action) { if (o && o[action] && o !== Y) { return o[action].call(o, f, c); } else { switch (A.test(o)) { case 1: return A[action](o, f, c); case 2: return A[action](Y.Array(o, 0, true), f, c); default: return Y.Object[action](o, f, c, proto); } } } /** Augments the _receiver_ with prototype properties from the _supplier_. The receiver may be a constructor function or an object. The supplier must be a constructor function. If the _receiver_ is an object, then the _supplier_ constructor will be called immediately after _receiver_ is augmented, with _receiver_ as the `this` object. If the _receiver_ is a constructor function, then all prototype methods of _supplier_ that are copied to _receiver_ will be sequestered, and the _supplier_ constructor will not be called immediately. The first time any sequestered method is called on the _receiver_'s prototype, all sequestered methods will be immediately copied to the _receiver_'s prototype, the _supplier_'s constructor will be executed, and finally the newly unsequestered method that was called will be executed. This sequestering logic sounds like a bunch of complicated voodoo, but it makes it cheap to perform frequent augmentation by ensuring that suppliers' constructors are only called if a supplied method is actually used. If none of the supplied methods is ever used, then there's no need to take the performance hit of calling the _supplier_'s constructor. @method augment @param {Function|Object} receiver Object or function to be augmented. @param {Function} supplier Function that supplies the prototype properties with which to augment the _receiver_. @param {Boolean} [overwrite=false] If `true`, properties already on the receiver will be overwritten if found on the supplier's prototype. @param {String[]} [whitelist] An array of property names. If specified, only the whitelisted prototype properties will be applied to the receiver, and all others will be ignored. @param {Array|any} [args] Argument or array of arguments to pass to the supplier's constructor when initializing. @return {Function} Augmented object. @for YUI **/ Y.augment = function (receiver, supplier, overwrite, whitelist, args) { var rProto = receiver.prototype, sequester = rProto && supplier, sProto = supplier.prototype, to = rProto || receiver, copy, newPrototype, replacements, sequestered, unsequester; args = args ? Y.Array(args) : []; if (sequester) { newPrototype = {}; replacements = {}; sequestered = {}; copy = function (value, key) { if (overwrite || !(key in rProto)) { if (toString.call(value) === '[object Function]') { sequestered[key] = value; newPrototype[key] = replacements[key] = function () { return unsequester(this, value, arguments); }; } else { newPrototype[key] = value; } } }; unsequester = function (instance, fn, fnArgs) { // Unsequester all sequestered functions. for (var key in sequestered) { if (hasOwn.call(sequestered, key) && instance[key] === replacements[key]) { instance[key] = sequestered[key]; } } // Execute the supplier constructor. supplier.apply(instance, args); // Finally, execute the original sequestered function. return fn.apply(instance, fnArgs); }; if (whitelist) { Y.Array.each(whitelist, function (name) { if (name in sProto) { copy(sProto[name], name); } }); } else { Y.Object.each(sProto, copy, null, true); } } Y.mix(to, newPrototype || sProto, overwrite, whitelist); if (!sequester) { supplier.apply(to, args); } return receiver; }; /** * Copies object properties from the supplier to the receiver. If the target has * the property, and the property is an object, the target object will be * augmented with the supplier's value. * * @method aggregate * @param {Object} receiver Object to receive the augmentation. * @param {Object} supplier Object that supplies the properties with which to * augment the receiver. * @param {Boolean} [overwrite=false] If `true`, properties already on the receiver * will be overwritten if found on the supplier. * @param {String[]} [whitelist] Whitelist. If supplied, only properties in this * list will be applied to the receiver. * @return {Object} Augmented object. */ Y.aggregate = function(r, s, ov, wl) { return Y.mix(r, s, ov, wl, 0, true); }; /** * Utility to set up the prototype, constructor and superclass properties to * support an inheritance strategy that can chain constructors and methods. * Static members will not be inherited. * * @method extend * @param {function} r the object to modify. * @param {function} s the object to inherit. * @param {object} px prototype properties to add/override. * @param {object} sx static properties to add/override. * @return {object} the extended object. */ Y.extend = function(r, s, px, sx) { if (!s || !r) { Y.error('extend failed, verify dependencies'); } var sp = s.prototype, rp = Y.Object(sp); r.prototype = rp; rp.constructor = r; r.superclass = sp; // assign constructor property if (s != Object && sp.constructor == OP.constructor) { sp.constructor = s; } // add prototype overrides if (px) { Y.mix(rp, px, true); } // add object overrides if (sx) { Y.mix(r, sx, true); } return r; }; /** * Executes the supplied function for each item in * a collection. Supports arrays, objects, and * NodeLists * @method each * @param {object} o the object to iterate. * @param {function} f the function to execute. This function * receives the value, key, and object as parameters. * @param {object} c the execution context for the function. * @param {boolean} proto if true, prototype properties are * iterated on objects. * @return {YUI} the YUI instance. */ Y.each = function(o, f, c, proto) { return dispatch(o, f, c, proto, 'each'); }; /** * Executes the supplied function for each item in * a collection. The operation stops if the function * returns true. Supports arrays, objects, and * NodeLists. * @method some * @param {object} o the object to iterate. * @param {function} f the function to execute. This function * receives the value, key, and object as parameters. * @param {object} c the execution context for the function. * @param {boolean} proto if true, prototype properties are * iterated on objects. * @return {boolean} true if the function ever returns true, * false otherwise. */ Y.some = function(o, f, c, proto) { return dispatch(o, f, c, proto, 'some'); }; /** Deep object/array copy. Function clones are actually wrappers around the original function. Array-like objects are treated as arrays. Primitives are returned untouched. Optionally, a function can be provided to handle other data types, filter keys, validate values, etc. **Note:** Cloning a non-trivial object is a reasonably heavy operation, due to the need to recursively iterate down non-primitive properties. Clone should be used only when a deep clone down to leaf level properties is explicitly required. This method will also In many cases (for example, when trying to isolate objects used as hashes for configuration properties), a shallow copy, using `Y.merge()` is normally sufficient. If more than one level of isolation is required, `Y.merge()` can be used selectively at each level which needs to be isolated from the original without going all the way to leaf properties. @method clone @param {object} o what to clone. @param {boolean} safe if true, objects will not have prototype items from the source. If false, they will. In this case, the original is initially protected, but the clone is not completely immune from changes to the source object prototype. Also, cloned prototype items that are deleted from the clone will result in the value of the source prototype being exposed. If operating on a non-safe clone, items should be nulled out rather than deleted. @param {function} f optional function to apply to each item in a collection; it will be executed prior to applying the value to the new object. Return false to prevent the copy. @param {object} c optional execution context for f. @param {object} owner Owner object passed when clone is iterating an object. Used to set up context for cloned functions. @param {object} cloned hash of previously cloned objects to avoid multiple clones. @return {Array|Object} the cloned object. **/ Y.clone = function(o, safe, f, c, owner, cloned) { var o2, marked, stamp; // Does not attempt to clone: // // * Non-typeof-object values, "primitive" values don't need cloning. // // * YUI instances, cloning complex object like YUI instances is not // advised, this is like cloning the world. // // * DOM nodes (#2528250), common host objects like DOM nodes cannot be // "subclassed" in Firefox and old versions of IE. Trying to use // `Object.create()` or `Y.extend()` on a DOM node will throw an error in // these browsers. // // Instad, the passed-in `o` will be return as-is when it matches one of the // above criteria. if (!L.isObject(o) || Y.instanceOf(o, YUI) || (o.addEventListener || o.attachEvent)) { return o; } marked = cloned || {}; switch (L.type(o)) { case 'date': return new Date(o); case 'regexp': // if we do this we need to set the flags too // return new RegExp(o.source); return o; case 'function': // o2 = Y.bind(o, owner); // break; return o; case 'array': o2 = []; break; default: // #2528250 only one clone of a given object should be created. if (o[CLONE_MARKER]) { return marked[o[CLONE_MARKER]]; } stamp = Y.guid(); o2 = (safe) ? {} : Y.Object(o); o[CLONE_MARKER] = stamp; marked[stamp] = o; } Y.each(o, function(v, k) { if ((k || k === 0) && (!f || (f.call(c || this, v, k, this, o) !== false))) { if (k !== CLONE_MARKER) { if (k == 'prototype') { // skip the prototype // } else if (o[k] === o) { // this[k] = this; } else { this[k] = Y.clone(v, safe, f, c, owner || o, marked); } } } }, o2); if (!cloned) { Y.Object.each(marked, function(v, k) { if (v[CLONE_MARKER]) { try { delete v[CLONE_MARKER]; } catch (e) { v[CLONE_MARKER] = null; } } }, this); marked = null; } return o2; }; /** * Returns a function that will execute the supplied function in the * supplied object's context, optionally adding any additional * supplied parameters to the beginning of the arguments collection the * supplied to the function. * * @method bind * @param {Function|String} f the function to bind, or a function name * to execute on the context object. * @param {object} c the execution context. * @param {any} args* 0..n arguments to include before the arguments the * function is executed with. * @return {function} the wrapped function. */ Y.bind = function(f, c) { var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null; return function() { var fn = L.isString(f) ? c[f] : f, args = (xargs) ? xargs.concat(Y.Array(arguments, 0, true)) : arguments; return fn.apply(c || fn, args); }; }; /** * Returns a function that will execute the supplied function in the * supplied object's context, optionally adding any additional * supplied parameters to the end of the arguments the function * is executed with. * * @method rbind * @param {Function|String} f the function to bind, or a function name * to execute on the context object. * @param {object} c the execution context. * @param {any} args* 0..n arguments to append to the end of * arguments collection supplied to the function. * @return {function} the wrapped function. */ Y.rbind = function(f, c) { var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null; return function() { var fn = L.isString(f) ? c[f] : f, args = (xargs) ? Y.Array(arguments, 0, true).concat(xargs) : arguments; return fn.apply(c || fn, args); }; }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('features', function (Y, NAME) { var feature_tests = {}; /** Contains the core of YUI's feature test architecture. @module features */ /** * Feature detection * @class Features * @static */ Y.mix(Y.namespace('Features'), { /** * Object hash of all registered feature tests * @property tests * @type Object */ tests: feature_tests, /** * Add a test to the system * * ``` * Y.Features.add("load", "1", {}); * ``` * * @method add * @param {String} cat The category, right now only 'load' is supported * @param {String} name The number sequence of the test, how it's reported in the URL or config: 1, 2, 3 * @param {Object} o Object containing test properties * @param {String} o.name The name of the test * @param {Function} o.test The test function to execute, the only argument to the function is the `Y` instance * @param {String} o.trigger The module that triggers this test. */ add: function(cat, name, o) { feature_tests[cat] = feature_tests[cat] || {}; feature_tests[cat][name] = o; }, /** * Execute all tests of a given category and return the serialized results * * ``` * caps=1:1;2:1;3:0 * ``` * @method all * @param {String} cat The category to execute * @param {Array} args The arguments to pass to the test function * @return {String} A semi-colon separated string of tests and their success/failure: 1:1;2:1;3:0 */ all: function(cat, args) { var cat_o = feature_tests[cat], // results = {}; result = []; if (cat_o) { Y.Object.each(cat_o, function(v, k) { result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0)); }); } return (result.length) ? result.join(';') : ''; }, /** * Run a sepecific test and return a Boolean response. * * ``` * Y.Features.test("load", "1"); * ``` * * @method test * @param {String} cat The category of the test to run * @param {String} name The name of the test to run * @param {Array} args The arguments to pass to the test function * @return {Boolean} True or false if the test passed/failed. */ test: function(cat, name, args) { args = args || []; var result, ua, test, cat_o = feature_tests[cat], feature = cat_o && cat_o[name]; if (!feature) { } else { result = feature.result; if (Y.Lang.isUndefined(result)) { ua = feature.ua; if (ua) { result = (Y.UA[ua]); } test = feature.test; if (test && ((!ua) || result)) { result = test.apply(Y, args); } feature.result = result; } } return result; } }); // Y.Features.add("load", "1", {}); // Y.Features.test("load", "1"); // caps=1:1;2:0;3:1; /* This file is auto-generated by (yogi loader --yes --mix --start ../) */ /*jshint maxlen:900, eqeqeq: false */ var add = Y.Features.add; // app-transitions-native add('load', '0', { "name": "app-transitions-native", "test": function (Y) { var doc = Y.config.doc, node = doc ? doc.documentElement : null; if (node && node.style) { return ('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return false; }, "trigger": "app-transitions" }); // autocomplete-list-keys add('load', '1', { "name": "autocomplete-list-keys", "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }); // dd-gestures add('load', '2', { "name": "dd-gestures", "trigger": "dd-drag", "ua": "touchEnabled" }); // dom-style-ie add('load', '3', { "name": "dom-style-ie", "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }); // editor-para-ie add('load', '4', { "name": "editor-para-ie", "trigger": "editor-para", "ua": "ie", "when": "instead" }); // event-base-ie add('load', '5', { "name": "event-base-ie", "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }); // graphics-canvas add('load', '6', { "name": "graphics-canvas", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-canvas-default add('load', '7', { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-svg add('load', '8', { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-svg-default add('load', '9', { "name": "graphics-svg-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-vml add('load', '10', { "name": "graphics-vml", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // graphics-vml-default add('load', '11', { "name": "graphics-vml-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // history-hash-ie add('load', '12', { "name": "history-hash-ie", "test": function (Y) { var docMode = Y.config.doc && Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }); // io-nodejs add('load', '13', { "name": "io-nodejs", "trigger": "io-base", "ua": "nodejs" }); // json-parse-shim add('load', '14', { "name": "json-parse-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONParse !== false && !!Native; function workingNative( k, v ) { return k === "ok" ? true : v; } // Double check basic functionality. This is mainly to catch early broken // implementations of the JSON API in Firefox 3.1 beta1 and beta2 if ( nativeSupport ) { try { nativeSupport = ( Native.parse( '{"ok":false}', workingNative ) ).ok; } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-parse" }); // json-stringify-shim add('load', '15', { "name": "json-stringify-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONStringify !== false && !!Native; // Double check basic native functionality. This is primarily to catch broken // early JSON API implementations in Firefox 3.1 beta1 and beta2. if ( nativeSupport ) { try { nativeSupport = ( '0' === Native.stringify(0) ); } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-stringify" }); // scrollview-base-ie add('load', '16', { "name": "scrollview-base-ie", "trigger": "scrollview-base", "ua": "ie" }); // selector-css2 add('load', '17', { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }); // transition-timer add('load', '18', { "name": "transition-timer", "test": function (Y) { var DOCUMENT = Y.config.doc, node = (DOCUMENT) ? DOCUMENT.documentElement: null, ret = true; if (node && node.style) { ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return ret; }, "trigger": "transition" }); // widget-base-ie add('load', '19', { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }); // yql-jsonp add('load', '20', { "name": "yql-jsonp", "test": function (Y) { /* Only load the JSONP module when not in nodejs or winjs TODO Make the winjs module a CORS module */ return (!Y.UA.nodejs && !Y.UA.winjs); }, "trigger": "yql", "when": "after" }); // yql-nodejs add('load', '21', { "name": "yql-nodejs", "trigger": "yql", "ua": "nodejs", "when": "after" }); // yql-winjs add('load', '22', { "name": "yql-winjs", "trigger": "yql", "ua": "winjs", "when": "after" }); }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('dom-core', function (Y, NAME) { var NODE_TYPE = 'nodeType', OWNER_DOCUMENT = 'ownerDocument', DOCUMENT_ELEMENT = 'documentElement', DEFAULT_VIEW = 'defaultView', PARENT_WINDOW = 'parentWindow', TAG_NAME = 'tagName', PARENT_NODE = 'parentNode', PREVIOUS_SIBLING = 'previousSibling', NEXT_SIBLING = 'nextSibling', CONTAINS = 'contains', COMPARE_DOCUMENT_POSITION = 'compareDocumentPosition', EMPTY_ARRAY = [], // IE < 8 throws on node.contains(textNode) supportsContainsTextNode = (function() { var node = Y.config.doc.createElement('div'), textNode = node.appendChild(Y.config.doc.createTextNode('')), result = false; try { result = node.contains(textNode); } catch(e) {} return result; })(), /** * The DOM utility provides a cross-browser abtraction layer * normalizing DOM tasks, and adds extra helper functionality * for other common tasks. * @module dom * @main dom * @submodule dom-base * @for DOM * */ /** * Provides DOM helper methods. * @class DOM * */ Y_DOM = { /** * Returns the HTMLElement with the given ID (Wrapper for document.getElementById). * @method byId * @param {String} id the id attribute * @param {Object} doc optional The document to search. Defaults to current document * @return {HTMLElement | null} The HTMLElement with the id, or null if none found. */ byId: function(id, doc) { // handle dupe IDs and IE name collision return Y_DOM.allById(id, doc)[0] || null; }, getId: function(node) { var id; // HTMLElement returned from FORM when INPUT name === "id" // IE < 8: HTMLCollection returned when INPUT id === "id" // via both getAttribute and form.id if (node.id && !node.id.tagName && !node.id.item) { id = node.id; } else if (node.attributes && node.attributes.id) { id = node.attributes.id.value; } return id; }, setId: function(node, id) { if (node.setAttribute) { node.setAttribute('id', id); } else { node.id = id; } }, /* * Finds the ancestor of the element. * @method ancestor * @param {HTMLElement} element The html element. * @param {Function} fn optional An optional boolean test to apply. * The optional function is passed the current DOM node being tested as its only argument. * If no function is given, the parentNode is returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @return {HTMLElement | null} The matching DOM node or null if none found. */ ancestor: function(element, fn, testSelf, stopFn) { var ret = null; if (testSelf) { ret = (!fn || fn(element)) ? element : null; } return ret || Y_DOM.elementByAxis(element, PARENT_NODE, fn, null, stopFn); }, /* * Finds the ancestors of the element. * @method ancestors * @param {HTMLElement} element The html element. * @param {Function} fn optional An optional boolean test to apply. * The optional function is passed the current DOM node being tested as its only argument. * If no function is given, all ancestors are returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @return {Array} An array containing all matching DOM nodes. */ ancestors: function(element, fn, testSelf, stopFn) { var ancestor = element, ret = []; while ((ancestor = Y_DOM.ancestor(ancestor, fn, testSelf, stopFn))) { testSelf = false; if (ancestor) { ret.unshift(ancestor); if (stopFn && stopFn(ancestor)) { return ret; } } } return ret; }, /** * Searches the element by the given axis for the first matching element. * @method elementByAxis * @param {HTMLElement} element The html element. * @param {String} axis The axis to search (parentNode, nextSibling, previousSibling). * @param {Function} fn optional An optional boolean test to apply. * @param {Boolean} all optional Whether all node types should be returned, or just element nodes. * The optional function is passed the current HTMLElement being tested as its only argument. * If no function is given, the first element is returned. * @return {HTMLElement | null} The matching element or null if none found. */ elementByAxis: function(element, axis, fn, all, stopAt) { while (element && (element = element[axis])) { // NOTE: assignment if ( (all || element[TAG_NAME]) && (!fn || fn(element)) ) { return element; } if (stopAt && stopAt(element)) { return null; } } return null; }, /** * Determines whether or not one HTMLElement is or contains another HTMLElement. * @method contains * @param {HTMLElement} element The containing html element. * @param {HTMLElement} needle The html element that may be contained. * @return {Boolean} Whether or not the element is or contains the needle. */ contains: function(element, needle) { var ret = false; if ( !needle || !element || !needle[NODE_TYPE] || !element[NODE_TYPE]) { ret = false; } else if (element[CONTAINS] && // IE < 8 throws on node.contains(textNode) so fall back to brute. // Falling back for other nodeTypes as well. (needle[NODE_TYPE] === 1 || supportsContainsTextNode)) { ret = element[CONTAINS](needle); } else if (element[COMPARE_DOCUMENT_POSITION]) { // Match contains behavior (node.contains(node) === true). // Needed for Firefox < 4. if (element === needle || !!(element[COMPARE_DOCUMENT_POSITION](needle) & 16)) { ret = true; } } else { ret = Y_DOM._bruteContains(element, needle); } return ret; }, /** * Determines whether or not the HTMLElement is part of the document. * @method inDoc * @param {HTMLElement} element The containing html element. * @param {HTMLElement} doc optional The document to check. * @return {Boolean} Whether or not the element is attached to the document. */ inDoc: function(element, doc) { var ret = false, rootNode; if (element && element.nodeType) { (doc) || (doc = element[OWNER_DOCUMENT]); rootNode = doc[DOCUMENT_ELEMENT]; // contains only works with HTML_ELEMENT if (rootNode && rootNode.contains && element.tagName) { ret = rootNode.contains(element); } else { ret = Y_DOM.contains(rootNode, element); } } return ret; }, allById: function(id, root) { root = root || Y.config.doc; var nodes = [], ret = [], i, node; if (root.querySelectorAll) { ret = root.querySelectorAll('[id="' + id + '"]'); } else if (root.all) { nodes = root.all(id); if (nodes) { // root.all may return HTMLElement or HTMLCollection. // some elements are also HTMLCollection (FORM, SELECT). if (nodes.nodeName) { if (nodes.id === id) { // avoid false positive on name ret.push(nodes); nodes = EMPTY_ARRAY; // done, no need to filter } else { // prep for filtering nodes = [nodes]; } } if (nodes.length) { // filter out matches on node.name // and element.id as reference to element with id === 'id' for (i = 0; node = nodes[i++];) { if (node.id === id || (node.attributes && node.attributes.id && node.attributes.id.value === id)) { ret.push(node); } } } } } else { ret = [Y_DOM._getDoc(root).getElementById(id)]; } return ret; }, isWindow: function(obj) { return !!(obj && obj.scrollTo && obj.document); }, _removeChildNodes: function(node) { while (node.firstChild) { node.removeChild(node.firstChild); } }, siblings: function(node, fn) { var nodes = [], sibling = node; while ((sibling = sibling[PREVIOUS_SIBLING])) { if (sibling[TAG_NAME] && (!fn || fn(sibling))) { nodes.unshift(sibling); } } sibling = node; while ((sibling = sibling[NEXT_SIBLING])) { if (sibling[TAG_NAME] && (!fn || fn(sibling))) { nodes.push(sibling); } } return nodes; }, /** * Brute force version of contains. * Used for browsers without contains support for non-HTMLElement Nodes (textNodes, etc). * @method _bruteContains * @private * @param {HTMLElement} element The containing html element. * @param {HTMLElement} needle The html element that may be contained. * @return {Boolean} Whether or not the element is or contains the needle. */ _bruteContains: function(element, needle) { while (needle) { if (element === needle) { return true; } needle = needle.parentNode; } return false; }, // TODO: move to Lang? /** * Memoizes dynamic regular expressions to boost runtime performance. * @method _getRegExp * @private * @param {String} str The string to convert to a regular expression. * @param {String} flags optional An optinal string of flags. * @return {RegExp} An instance of RegExp */ _getRegExp: function(str, flags) { flags = flags || ''; Y_DOM._regexCache = Y_DOM._regexCache || {}; if (!Y_DOM._regexCache[str + flags]) { Y_DOM._regexCache[str + flags] = new RegExp(str, flags); } return Y_DOM._regexCache[str + flags]; }, // TODO: make getDoc/Win true privates? /** * returns the appropriate document. * @method _getDoc * @private * @param {HTMLElement} element optional Target element. * @return {Object} The document for the given element or the default document. */ _getDoc: function(element) { var doc = Y.config.doc; if (element) { doc = (element[NODE_TYPE] === 9) ? element : // element === document element[OWNER_DOCUMENT] || // element === DOM node element.document || // element === window Y.config.doc; // default } return doc; }, /** * returns the appropriate window. * @method _getWin * @private * @param {HTMLElement} element optional Target element. * @return {Object} The window for the given element or the default window. */ _getWin: function(element) { var doc = Y_DOM._getDoc(element); return doc[DEFAULT_VIEW] || doc[PARENT_WINDOW] || Y.config.win; }, _batch: function(nodes, fn, arg1, arg2, arg3, etc) { fn = (typeof fn === 'string') ? Y_DOM[fn] : fn; var result, i = 0, node, ret; if (fn && nodes) { while ((node = nodes[i++])) { result = result = fn.call(Y_DOM, node, arg1, arg2, arg3, etc); if (typeof result !== 'undefined') { (ret) || (ret = []); ret.push(result); } } } return (typeof ret !== 'undefined') ? ret : nodes; }, generateID: function(el) { var id = el.id; if (!id) { id = Y.stamp(el); el.id = id; } return id; } }; Y.DOM = Y_DOM; }, '@VERSION@', {"requires": ["oop", "features"]}); YUI.add('dom-base', function (Y, NAME) { /** * @for DOM * @module dom */ var documentElement = Y.config.doc.documentElement, Y_DOM = Y.DOM, TAG_NAME = 'tagName', OWNER_DOCUMENT = 'ownerDocument', EMPTY_STRING = '', addFeature = Y.Features.add, testFeature = Y.Features.test; Y.mix(Y_DOM, { /** * Returns the text content of the HTMLElement. * @method getText * @param {HTMLElement} element The html element. * @return {String} The text content of the element (includes text of any descending elements). */ getText: (documentElement.textContent !== undefined) ? function(element) { var ret = ''; if (element) { ret = element.textContent; } return ret || ''; } : function(element) { var ret = ''; if (element) { ret = element.innerText || element.nodeValue; // might be a textNode } return ret || ''; }, /** * Sets the text content of the HTMLElement. * @method setText * @param {HTMLElement} element The html element. * @param {String} content The content to add. */ setText: (documentElement.textContent !== undefined) ? function(element, content) { if (element) { element.textContent = content; } } : function(element, content) { if ('innerText' in element) { element.innerText = content; } else if ('nodeValue' in element) { element.nodeValue = content; } }, CUSTOM_ATTRIBUTES: (!documentElement.hasAttribute) ? { // IE < 8 'for': 'htmlFor', 'class': 'className' } : { // w3c 'htmlFor': 'for', 'className': 'class' }, /** * Provides a normalized attribute interface. * @method setAttribute * @param {HTMLElement} el The target element for the attribute. * @param {String} attr The attribute to set. * @param {String} val The value of the attribute. */ setAttribute: function(el, attr, val, ieAttr) { if (el && attr && el.setAttribute) { attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr; el.setAttribute(attr, val, ieAttr); } }, /** * Provides a normalized attribute interface. * @method getAttribute * @param {HTMLElement} el The target element for the attribute. * @param {String} attr The attribute to get. * @return {String} The current value of the attribute. */ getAttribute: function(el, attr, ieAttr) { ieAttr = (ieAttr !== undefined) ? ieAttr : 2; var ret = ''; if (el && attr && el.getAttribute) { attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr; ret = el.getAttribute(attr, ieAttr); if (ret === null) { ret = ''; // per DOM spec } } return ret; }, VALUE_SETTERS: {}, VALUE_GETTERS: {}, getValue: function(node) { var ret = '', // TODO: return null? getter; if (node && node[TAG_NAME]) { getter = Y_DOM.VALUE_GETTERS[node[TAG_NAME].toLowerCase()]; if (getter) { ret = getter(node); } else { ret = node.value; } } // workaround for IE8 JSON stringify bug // which converts empty string values to null if (ret === EMPTY_STRING) { ret = EMPTY_STRING; // for real } return (typeof ret === 'string') ? ret : ''; }, setValue: function(node, val) { var setter; if (node && node[TAG_NAME]) { setter = Y_DOM.VALUE_SETTERS[node[TAG_NAME].toLowerCase()]; if (setter) { setter(node, val); } else { node.value = val; } } }, creators: {} }); addFeature('value-set', 'select', { test: function() { var node = Y.config.doc.createElement('select'); node.innerHTML = '<option>1</option><option>2</option>'; node.value = '2'; return (node.value && node.value === '2'); } }); if (!testFeature('value-set', 'select')) { Y_DOM.VALUE_SETTERS.select = function(node, val) { for (var i = 0, options = node.getElementsByTagName('option'), option; option = options[i++];) { if (Y_DOM.getValue(option) === val) { option.selected = true; //Y_DOM.setAttribute(option, 'selected', 'selected'); break; } } }; } Y.mix(Y_DOM.VALUE_GETTERS, { button: function(node) { return (node.attributes && node.attributes.value) ? node.attributes.value.value : ''; } }); Y.mix(Y_DOM.VALUE_SETTERS, { // IE: node.value changes the button text, which should be handled via innerHTML button: function(node, val) { var attr = node.attributes.value; if (!attr) { attr = node[OWNER_DOCUMENT].createAttribute('value'); node.setAttributeNode(attr); } attr.value = val; } }); Y.mix(Y_DOM.VALUE_GETTERS, { option: function(node) { var attrs = node.attributes; return (attrs.value && attrs.value.specified) ? node.value : node.text; }, select: function(node) { var val = node.value, options = node.options; if (options && options.length) { // TODO: implement multipe select if (node.multiple) { } else if (node.selectedIndex > -1) { val = Y_DOM.getValue(options[node.selectedIndex]); } } return val; } }); var addClass, hasClass, removeClass; Y.mix(Y.DOM, { /** * Determines whether a DOM element has the given className. * @method hasClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to search for * @return {Boolean} Whether or not the element has the given class. */ hasClass: function(node, className) { var re = Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)'); return re.test(node.className); }, /** * Adds a class name to a given DOM element. * @method addClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to add to the class attribute */ addClass: function(node, className) { if (!Y.DOM.hasClass(node, className)) { // skip if already present node.className = Y.Lang.trim([node.className, className].join(' ')); } }, /** * Removes a class name from a given element. * @method removeClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to remove from the class attribute */ removeClass: function(node, className) { if (className && hasClass(node, className)) { node.className = Y.Lang.trim(node.className.replace(Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)'), ' ')); if ( hasClass(node, className) ) { // in case of multiple adjacent removeClass(node, className); } } }, /** * Replace a class with another class for a given element. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @for DOM * @param {HTMLElement} element The DOM element * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name */ replaceClass: function(node, oldC, newC) { removeClass(node, oldC); // remove first in case oldC === newC addClass(node, newC); }, /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @for DOM * @param {HTMLElement} element The DOM element * @param {String} className the class name to be toggled * @param {Boolean} addClass optional boolean to indicate whether class * should be added or removed regardless of current state */ toggleClass: function(node, className, force) { var add = (force !== undefined) ? force : !(hasClass(node, className)); if (add) { addClass(node, className); } else { removeClass(node, className); } } }); hasClass = Y.DOM.hasClass; removeClass = Y.DOM.removeClass; addClass = Y.DOM.addClass; var re_tag = /<([a-z]+)/i, Y_DOM = Y.DOM, addFeature = Y.Features.add, testFeature = Y.Features.test, creators = {}, createFromDIV = function(html, tag) { var div = Y.config.doc.createElement('div'), ret = true; div.innerHTML = html; if (!div.firstChild || div.firstChild.tagName !== tag.toUpperCase()) { ret = false; } return ret; }, re_tbody = /(?:\/(?:thead|tfoot|tbody|caption|col|colgroup)>)+\s*<tbody/, TABLE_OPEN = '<table>', TABLE_CLOSE = '</table>'; Y.mix(Y.DOM, { _fragClones: {}, _create: function(html, doc, tag) { tag = tag || 'div'; var frag = Y_DOM._fragClones[tag]; if (frag) { frag = frag.cloneNode(false); } else { frag = Y_DOM._fragClones[tag] = doc.createElement(tag); } frag.innerHTML = html; return frag; }, _children: function(node, tag) { var i = 0, children = node.children, childNodes, hasComments, child; if (children && children.tags) { // use tags filter when possible if (tag) { children = node.children.tags(tag); } else { // IE leaks comments into children hasComments = children.tags('!').length; } } if (!children || (!children.tags && tag) || hasComments) { childNodes = children || node.childNodes; children = []; while ((child = childNodes[i++])) { if (child.nodeType === 1) { if (!tag || tag === child.tagName) { children.push(child); } } } } return children || []; }, /** * Creates a new dom node using the provided markup string. * @method create * @param {String} html The markup used to create the element * @param {HTMLDocument} doc An optional document context * @return {HTMLElement|DocumentFragment} returns a single HTMLElement * when creating one node, and a documentFragment when creating * multiple nodes. */ create: function(html, doc) { if (typeof html === 'string') { html = Y.Lang.trim(html); // match IE which trims whitespace from innerHTML } doc = doc || Y.config.doc; var m = re_tag.exec(html), create = Y_DOM._create, custom = creators, ret = null, creator, tag, nodes; if (html != undefined) { // not undefined or null if (m && m[1]) { creator = custom[m[1].toLowerCase()]; if (typeof creator === 'function') { create = creator; } else { tag = creator; } } nodes = create(html, doc, tag).childNodes; if (nodes.length === 1) { // return single node, breaking parentNode ref from "fragment" ret = nodes[0].parentNode.removeChild(nodes[0]); } else if (nodes[0] && nodes[0].className === 'yui3-big-dummy') { // using dummy node to preserve some attributes (e.g. OPTION not selected) if (nodes.length === 2) { ret = nodes[0].nextSibling; } else { nodes[0].parentNode.removeChild(nodes[0]); ret = Y_DOM._nl2frag(nodes, doc); } } else { // return multiple nodes as a fragment ret = Y_DOM._nl2frag(nodes, doc); } } return ret; }, _nl2frag: function(nodes, doc) { var ret = null, i, len; if (nodes && (nodes.push || nodes.item) && nodes[0]) { doc = doc || nodes[0].ownerDocument; ret = doc.createDocumentFragment(); if (nodes.item) { // convert live list to static array nodes = Y.Array(nodes, 0, true); } for (i = 0, len = nodes.length; i < len; i++) { ret.appendChild(nodes[i]); } } // else inline with log for minification return ret; }, /** * Inserts content in a node at the given location * @method addHTML * @param {HTMLElement} node The node to insert into * @param {HTMLElement | Array | HTMLCollection} content The content to be inserted * @param {HTMLElement} where Where to insert the content * If no "where" is given, content is appended to the node * Possible values for "where" * <dl> * <dt>HTMLElement</dt> * <dd>The element to insert before</dd> * <dt>"replace"</dt> * <dd>Replaces the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts before the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts content before the node</dd> * <dt>"after"</dt> * <dd>Inserts content after the node</dd> * </dl> */ addHTML: function(node, content, where) { var nodeParent = node.parentNode, i = 0, item, ret = content, newNode; if (content != undefined) { // not null or undefined (maybe 0) if (content.nodeType) { // DOM node, just add it newNode = content; } else if (typeof content == 'string' || typeof content == 'number') { ret = newNode = Y_DOM.create(content); } else if (content[0] && content[0].nodeType) { // array or collection newNode = Y.config.doc.createDocumentFragment(); while ((item = content[i++])) { newNode.appendChild(item); // append to fragment for insertion } } } if (where) { if (newNode && where.parentNode) { // insert regardless of relationship to node where.parentNode.insertBefore(newNode, where); } else { switch (where) { case 'replace': while (node.firstChild) { node.removeChild(node.firstChild); } if (newNode) { // allow empty content to clear node node.appendChild(newNode); } break; case 'before': if (newNode) { nodeParent.insertBefore(newNode, node); } break; case 'after': if (newNode) { if (node.nextSibling) { // IE errors if refNode is null nodeParent.insertBefore(newNode, node.nextSibling); } else { nodeParent.appendChild(newNode); } } break; default: if (newNode) { node.appendChild(newNode); } } } } else if (newNode) { node.appendChild(newNode); } return ret; }, wrap: function(node, html) { var parent = (html && html.nodeType) ? html : Y.DOM.create(html), nodes = parent.getElementsByTagName('*'); if (nodes.length) { parent = nodes[nodes.length - 1]; } if (node.parentNode) { node.parentNode.replaceChild(parent, node); } parent.appendChild(node); }, unwrap: function(node) { var parent = node.parentNode, lastChild = parent.lastChild, next = node, grandparent; if (parent) { grandparent = parent.parentNode; if (grandparent) { node = parent.firstChild; while (node !== lastChild) { next = node.nextSibling; grandparent.insertBefore(node, parent); node = next; } grandparent.replaceChild(lastChild, parent); } else { parent.removeChild(node); } } } }); addFeature('innerhtml', 'table', { test: function() { var node = Y.config.doc.createElement('table'); try { node.innerHTML = '<tbody></tbody>'; } catch(e) { return false; } return (node.firstChild && node.firstChild.nodeName === 'TBODY'); } }); addFeature('innerhtml-div', 'tr', { test: function() { return createFromDIV('<tr></tr>', 'tr'); } }); addFeature('innerhtml-div', 'script', { test: function() { return createFromDIV('<script></script>', 'script'); } }); if (!testFeature('innerhtml', 'table')) { // TODO: thead/tfoot with nested tbody // IE adds TBODY when creating TABLE elements (which may share this impl) creators.tbody = function(html, doc) { var frag = Y_DOM.create(TABLE_OPEN + html + TABLE_CLOSE, doc), tb = Y.DOM._children(frag, 'tbody')[0]; if (frag.children.length > 1 && tb && !re_tbody.test(html)) { tb.parentNode.removeChild(tb); // strip extraneous tbody } return frag; }; } if (!testFeature('innerhtml-div', 'script')) { creators.script = function(html, doc) { var frag = doc.createElement('div'); frag.innerHTML = '-' + html; frag.removeChild(frag.firstChild); return frag; }; creators.link = creators.style = creators.script; } if (!testFeature('innerhtml-div', 'tr')) { Y.mix(creators, { option: function(html, doc) { return Y_DOM.create('<select><option class="yui3-big-dummy" selected></option>' + html + '</select>', doc); }, tr: function(html, doc) { return Y_DOM.create('<tbody>' + html + '</tbody>', doc); }, td: function(html, doc) { return Y_DOM.create('<tr>' + html + '</tr>', doc); }, col: function(html, doc) { return Y_DOM.create('<colgroup>' + html + '</colgroup>', doc); }, tbody: 'table' }); Y.mix(creators, { legend: 'fieldset', th: creators.td, thead: creators.tbody, tfoot: creators.tbody, caption: creators.tbody, colgroup: creators.tbody, optgroup: creators.option }); } Y_DOM.creators = creators; Y.mix(Y.DOM, { /** * Sets the width of the element to the given size, regardless * of box model, border, padding, etc. * @method setWidth * @param {HTMLElement} element The DOM element. * @param {String|Number} size The pixel height to size to */ setWidth: function(node, size) { Y.DOM._setSize(node, 'width', size); }, /** * Sets the height of the element to the given size, regardless * of box model, border, padding, etc. * @method setHeight * @param {HTMLElement} element The DOM element. * @param {String|Number} size The pixel height to size to */ setHeight: function(node, size) { Y.DOM._setSize(node, 'height', size); }, _setSize: function(node, prop, val) { val = (val > 0) ? val : 0; var size = 0; node.style[prop] = val + 'px'; size = (prop === 'height') ? node.offsetHeight : node.offsetWidth; if (size > val) { val = val - (size - val); if (val < 0) { val = 0; } node.style[prop] = val + 'px'; } } }); }, '@VERSION@', {"requires": ["dom-core"]}); YUI.add('dom-style', function (Y, NAME) { (function(Y) { /** * Add style management functionality to DOM. * @module dom * @submodule dom-style * @for DOM */ var DOCUMENT_ELEMENT = 'documentElement', DEFAULT_VIEW = 'defaultView', OWNER_DOCUMENT = 'ownerDocument', STYLE = 'style', FLOAT = 'float', CSS_FLOAT = 'cssFloat', STYLE_FLOAT = 'styleFloat', TRANSPARENT = 'transparent', GET_COMPUTED_STYLE = 'getComputedStyle', GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect', WINDOW = Y.config.win, DOCUMENT = Y.config.doc, UNDEFINED = undefined, Y_DOM = Y.DOM, TRANSFORM = 'transform', TRANSFORMORIGIN = 'transformOrigin', VENDOR_TRANSFORM = [ 'WebkitTransform', 'MozTransform', 'OTransform', 'msTransform' ], re_color = /color$/i, re_unit = /width|height|top|left|right|bottom|margin|padding/i; Y.Array.each(VENDOR_TRANSFORM, function(val) { if (val in DOCUMENT[DOCUMENT_ELEMENT].style) { TRANSFORM = val; TRANSFORMORIGIN = val + "Origin"; } }); Y.mix(Y_DOM, { DEFAULT_UNIT: 'px', CUSTOM_STYLES: { }, /** * Sets a style property for a given element. * @method setStyle * @param {HTMLElement} An HTMLElement to apply the style to. * @param {String} att The style property to set. * @param {String|Number} val The value. */ setStyle: function(node, att, val, style) { style = style || node.style; var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES; if (style) { if (val === null || val === '') { // normalize unsetting val = ''; } else if (!isNaN(new Number(val)) && re_unit.test(att)) { // number values may need a unit val += Y_DOM.DEFAULT_UNIT; } if (att in CUSTOM_STYLES) { if (CUSTOM_STYLES[att].set) { CUSTOM_STYLES[att].set(node, val, style); return; // NOTE: return } else if (typeof CUSTOM_STYLES[att] === 'string') { att = CUSTOM_STYLES[att]; } } else if (att === '') { // unset inline styles att = 'cssText'; val = ''; } style[att] = val; } }, /** * Returns the current style value for the given property. * @method getStyle * @param {HTMLElement} An HTMLElement to get the style from. * @param {String} att The style property to get. */ getStyle: function(node, att, style) { style = style || node.style; var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES, val = ''; if (style) { if (att in CUSTOM_STYLES) { if (CUSTOM_STYLES[att].get) { return CUSTOM_STYLES[att].get(node, att, style); // NOTE: return } else if (typeof CUSTOM_STYLES[att] === 'string') { att = CUSTOM_STYLES[att]; } } val = style[att]; if (val === '') { // TODO: is empty string sufficient? val = Y_DOM[GET_COMPUTED_STYLE](node, att); } } return val; }, /** * Sets multiple style properties. * @method setStyles * @param {HTMLElement} node An HTMLElement to apply the styles to. * @param {Object} hash An object literal of property:value pairs. */ setStyles: function(node, hash) { var style = node.style; Y.each(hash, function(v, n) { Y_DOM.setStyle(node, n, v, style); }, Y_DOM); }, /** * Returns the computed style for the given node. * @method getComputedStyle * @param {HTMLElement} An HTMLElement to get the style from. * @param {String} att The style property to get. * @return {String} The computed value of the style property. */ getComputedStyle: function(node, att) { var val = '', doc = node[OWNER_DOCUMENT], computed; if (node[STYLE] && doc[DEFAULT_VIEW] && doc[DEFAULT_VIEW][GET_COMPUTED_STYLE]) { computed = doc[DEFAULT_VIEW][GET_COMPUTED_STYLE](node, null); if (computed) { // FF may be null in some cases (ticket #2530548) val = computed[att]; } } return val; } }); // normalize reserved word float alternatives ("cssFloat" or "styleFloat") if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][CSS_FLOAT] !== UNDEFINED) { Y_DOM.CUSTOM_STYLES[FLOAT] = CSS_FLOAT; } else if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][STYLE_FLOAT] !== UNDEFINED) { Y_DOM.CUSTOM_STYLES[FLOAT] = STYLE_FLOAT; } // fix opera computedStyle default color unit (convert to rgb) if (Y.UA.opera) { Y_DOM[GET_COMPUTED_STYLE] = function(node, att) { var view = node[OWNER_DOCUMENT][DEFAULT_VIEW], val = view[GET_COMPUTED_STYLE](node, '')[att]; if (re_color.test(att)) { val = Y.Color.toRGB(val); } return val; }; } // safari converts transparent to rgba(), others use "transparent" if (Y.UA.webkit) { Y_DOM[GET_COMPUTED_STYLE] = function(node, att) { var view = node[OWNER_DOCUMENT][DEFAULT_VIEW], val = view[GET_COMPUTED_STYLE](node, '')[att]; if (val === 'rgba(0, 0, 0, 0)') { val = TRANSPARENT; } return val; }; } Y.DOM._getAttrOffset = function(node, attr) { var val = Y.DOM[GET_COMPUTED_STYLE](node, attr), offsetParent = node.offsetParent, position, parentOffset, offset; if (val === 'auto') { position = Y.DOM.getStyle(node, 'position'); if (position === 'static' || position === 'relative') { val = 0; } else if (offsetParent && offsetParent[GET_BOUNDING_CLIENT_RECT]) { parentOffset = offsetParent[GET_BOUNDING_CLIENT_RECT]()[attr]; offset = node[GET_BOUNDING_CLIENT_RECT]()[attr]; if (attr === 'left' || attr === 'top') { val = offset - parentOffset; } else { val = parentOffset - node[GET_BOUNDING_CLIENT_RECT]()[attr]; } } } return val; }; Y.DOM._getOffset = function(node) { var pos, xy = null; if (node) { pos = Y_DOM.getStyle(node, 'position'); xy = [ parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'left'), 10), parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'top'), 10) ]; if ( isNaN(xy[0]) ) { // in case of 'auto' xy[0] = parseInt(Y_DOM.getStyle(node, 'left'), 10); // try inline if ( isNaN(xy[0]) ) { // default to offset value xy[0] = (pos === 'relative') ? 0 : node.offsetLeft || 0; } } if ( isNaN(xy[1]) ) { // in case of 'auto' xy[1] = parseInt(Y_DOM.getStyle(node, 'top'), 10); // try inline if ( isNaN(xy[1]) ) { // default to offset value xy[1] = (pos === 'relative') ? 0 : node.offsetTop || 0; } } } return xy; }; Y_DOM.CUSTOM_STYLES.transform = { set: function(node, val, style) { style[TRANSFORM] = val; }, get: function(node, style) { return Y_DOM[GET_COMPUTED_STYLE](node, TRANSFORM); } }; Y_DOM.CUSTOM_STYLES.transformOrigin = { set: function(node, val, style) { style[TRANSFORMORIGIN] = val; }, get: function(node, style) { return Y_DOM[GET_COMPUTED_STYLE](node, TRANSFORMORIGIN); } }; })(Y); (function(Y) { var PARSE_INT = parseInt, RE = RegExp; Y.Color = { KEYWORDS: { black: '000', silver: 'c0c0c0', gray: '808080', white: 'fff', maroon: '800000', red: 'f00', purple: '800080', fuchsia: 'f0f', green: '008000', lime: '0f0', olive: '808000', yellow: 'ff0', navy: '000080', blue: '00f', teal: '008080', aqua: '0ff' }, re_RGB: /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i, re_hex: /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i, re_hex3: /([0-9A-F])/gi, toRGB: function(val) { if (!Y.Color.re_RGB.test(val)) { val = Y.Color.toHex(val); } if(Y.Color.re_hex.exec(val)) { val = 'rgb(' + [ PARSE_INT(RE.$1, 16), PARSE_INT(RE.$2, 16), PARSE_INT(RE.$3, 16) ].join(', ') + ')'; } return val; }, toHex: function(val) { val = Y.Color.KEYWORDS[val] || val; if (Y.Color.re_RGB.exec(val)) { val = [ Number(RE.$1).toString(16), Number(RE.$2).toString(16), Number(RE.$3).toString(16) ]; for (var i = 0; i < val.length; i++) { if (val[i].length < 2) { val[i] = '0' + val[i]; } } val = val.join(''); } if (val.length < 6) { val = val.replace(Y.Color.re_hex3, '$1$1'); } if (val !== 'transparent' && val.indexOf('#') < 0) { val = '#' + val; } return val.toUpperCase(); } }; })(Y); }, '@VERSION@', {"requires": ["dom-base"]}); YUI.add('dom-style-ie', function (Y, NAME) { (function(Y) { var HAS_LAYOUT = 'hasLayout', PX = 'px', FILTER = 'filter', FILTERS = 'filters', OPACITY = 'opacity', AUTO = 'auto', BORDER_WIDTH = 'borderWidth', BORDER_TOP_WIDTH = 'borderTopWidth', BORDER_RIGHT_WIDTH = 'borderRightWidth', BORDER_BOTTOM_WIDTH = 'borderBottomWidth', BORDER_LEFT_WIDTH = 'borderLeftWidth', WIDTH = 'width', HEIGHT = 'height', TRANSPARENT = 'transparent', VISIBLE = 'visible', GET_COMPUTED_STYLE = 'getComputedStyle', UNDEFINED = undefined, documentElement = Y.config.doc.documentElement, testFeature = Y.Features.test, addFeature = Y.Features.add, // TODO: unit-less lineHeight (e.g. 1.22) re_unit = /^(\d[.\d]*)+(em|ex|px|gd|rem|vw|vh|vm|ch|mm|cm|in|pt|pc|deg|rad|ms|s|hz|khz|%){1}?/i, isIE8 = (Y.UA.ie >= 8), _getStyleObj = function(node) { return node.currentStyle || node.style; }, ComputedStyle = { CUSTOM_STYLES: {}, get: function(el, property) { var value = '', current; if (el) { current = _getStyleObj(el)[property]; if (property === OPACITY && Y.DOM.CUSTOM_STYLES[OPACITY]) { value = Y.DOM.CUSTOM_STYLES[OPACITY].get(el); } else if (!current || (current.indexOf && current.indexOf(PX) > -1)) { // no need to convert value = current; } else if (Y.DOM.IE.COMPUTED[property]) { // use compute function value = Y.DOM.IE.COMPUTED[property](el, property); } else if (re_unit.test(current)) { // convert to pixel value = ComputedStyle.getPixel(el, property) + PX; } else { value = current; } } return value; }, sizeOffsets: { width: ['Left', 'Right'], height: ['Top', 'Bottom'], top: ['Top'], bottom: ['Bottom'] }, getOffset: function(el, prop) { var current = _getStyleObj(el)[prop], // value of "width", "top", etc. capped = prop.charAt(0).toUpperCase() + prop.substr(1), // "Width", "Top", etc. offset = 'offset' + capped, // "offsetWidth", "offsetTop", etc. pixel = 'pixel' + capped, // "pixelWidth", "pixelTop", etc. sizeOffsets = ComputedStyle.sizeOffsets[prop], mode = el.ownerDocument.compatMode, value = ''; // IE pixelWidth incorrect for percent // manually compute by subtracting padding and border from offset size // NOTE: clientWidth/Height (size minus border) is 0 when current === AUTO so offsetHeight is used // reverting to auto from auto causes position stacking issues (old impl) if (current === AUTO || current.indexOf('%') > -1) { value = el['offset' + capped]; if (mode !== 'BackCompat') { if (sizeOffsets[0]) { value -= ComputedStyle.getPixel(el, 'padding' + sizeOffsets[0]); value -= ComputedStyle.getBorderWidth(el, 'border' + sizeOffsets[0] + 'Width', 1); } if (sizeOffsets[1]) { value -= ComputedStyle.getPixel(el, 'padding' + sizeOffsets[1]); value -= ComputedStyle.getBorderWidth(el, 'border' + sizeOffsets[1] + 'Width', 1); } } } else { // use style.pixelWidth, etc. to convert to pixels // need to map style.width to currentStyle (no currentStyle.pixelWidth) if (!el.style[pixel] && !el.style[prop]) { el.style[prop] = current; } value = el.style[pixel]; } return value + PX; }, borderMap: { thin: (isIE8) ? '1px' : '2px', medium: (isIE8) ? '3px': '4px', thick: (isIE8) ? '5px' : '6px' }, getBorderWidth: function(el, property, omitUnit) { var unit = omitUnit ? '' : PX, current = el.currentStyle[property]; if (current.indexOf(PX) < 0) { // look up keywords if a border exists if (ComputedStyle.borderMap[current] && el.currentStyle.borderStyle !== 'none') { current = ComputedStyle.borderMap[current]; } else { // otherwise no border (default is "medium") current = 0; } } return (omitUnit) ? parseFloat(current) : current; }, getPixel: function(node, att) { // use pixelRight to convert to px var val = null, style = _getStyleObj(node), styleRight = style.right, current = style[att]; node.style.right = current; val = node.style.pixelRight; node.style.right = styleRight; // revert return val; }, getMargin: function(node, att) { var val, style = _getStyleObj(node); if (style[att] == AUTO) { val = 0; } else { val = ComputedStyle.getPixel(node, att); } return val + PX; }, getVisibility: function(node, att) { var current; while ( (current = node.currentStyle) && current[att] == 'inherit') { // NOTE: assignment in test node = node.parentNode; } return (current) ? current[att] : VISIBLE; }, getColor: function(node, att) { var current = _getStyleObj(node)[att]; if (!current || current === TRANSPARENT) { Y.DOM.elementByAxis(node, 'parentNode', null, function(parent) { current = _getStyleObj(parent)[att]; if (current && current !== TRANSPARENT) { node = parent; return true; } }); } return Y.Color.toRGB(current); }, getBorderColor: function(node, att) { var current = _getStyleObj(node), val = current[att] || current.color; return Y.Color.toRGB(Y.Color.toHex(val)); } }, //fontSize: getPixelFont, IEComputed = {}; addFeature('style', 'computedStyle', { test: function() { return 'getComputedStyle' in Y.config.win; } }); addFeature('style', 'opacity', { test: function() { return 'opacity' in documentElement.style; } }); addFeature('style', 'filter', { test: function() { return 'filters' in documentElement; } }); // use alpha filter for IE opacity if (!testFeature('style', 'opacity') && testFeature('style', 'filter')) { Y.DOM.CUSTOM_STYLES[OPACITY] = { get: function(node) { var val = 100; try { // will error if no DXImageTransform val = node[FILTERS]['DXImageTransform.Microsoft.Alpha'][OPACITY]; } catch(e) { try { // make sure its in the document val = node[FILTERS]('alpha')[OPACITY]; } catch(err) { } } return val / 100; }, set: function(node, val, style) { var current, styleObj = _getStyleObj(node), currentFilter = styleObj[FILTER]; style = style || node.style; if (val === '') { // normalize inline style behavior current = (OPACITY in styleObj) ? styleObj[OPACITY] : 1; // revert to original opacity val = current; } if (typeof currentFilter == 'string') { // in case not appended style[FILTER] = currentFilter.replace(/alpha([^)]*\))/gi, '') + ((val < 1) ? 'alpha(' + OPACITY + '=' + val * 100 + ')' : ''); if (!style[FILTER]) { style.removeAttribute(FILTER); } if (!styleObj[HAS_LAYOUT]) { style.zoom = 1; // needs layout } } } }; } try { Y.config.doc.createElement('div').style.height = '-1px'; } catch(e) { // IE throws error on invalid style set; trap common cases Y.DOM.CUSTOM_STYLES.height = { set: function(node, val, style) { var floatVal = parseFloat(val); if (floatVal >= 0 || val === 'auto' || val === '') { style.height = val; } else { } } }; Y.DOM.CUSTOM_STYLES.width = { set: function(node, val, style) { var floatVal = parseFloat(val); if (floatVal >= 0 || val === 'auto' || val === '') { style.width = val; } else { } } }; } if (!testFeature('style', 'computedStyle')) { // TODO: top, right, bottom, left IEComputed[WIDTH] = IEComputed[HEIGHT] = ComputedStyle.getOffset; IEComputed.color = IEComputed.backgroundColor = ComputedStyle.getColor; IEComputed[BORDER_WIDTH] = IEComputed[BORDER_TOP_WIDTH] = IEComputed[BORDER_RIGHT_WIDTH] = IEComputed[BORDER_BOTTOM_WIDTH] = IEComputed[BORDER_LEFT_WIDTH] = ComputedStyle.getBorderWidth; IEComputed.marginTop = IEComputed.marginRight = IEComputed.marginBottom = IEComputed.marginLeft = ComputedStyle.getMargin; IEComputed.visibility = ComputedStyle.getVisibility; IEComputed.borderColor = IEComputed.borderTopColor = IEComputed.borderRightColor = IEComputed.borderBottomColor = IEComputed.borderLeftColor = ComputedStyle.getBorderColor; Y.DOM[GET_COMPUTED_STYLE] = ComputedStyle.get; Y.namespace('DOM.IE'); Y.DOM.IE.COMPUTED = IEComputed; Y.DOM.IE.ComputedStyle = ComputedStyle; } })(Y); }, '@VERSION@', {"requires": ["dom-style"]}); YUI.add('dom-screen', function (Y, NAME) { (function(Y) { /** * Adds position and region management functionality to DOM. * @module dom * @submodule dom-screen * @for DOM */ var DOCUMENT_ELEMENT = 'documentElement', COMPAT_MODE = 'compatMode', POSITION = 'position', FIXED = 'fixed', RELATIVE = 'relative', LEFT = 'left', TOP = 'top', _BACK_COMPAT = 'BackCompat', MEDIUM = 'medium', BORDER_LEFT_WIDTH = 'borderLeftWidth', BORDER_TOP_WIDTH = 'borderTopWidth', GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect', GET_COMPUTED_STYLE = 'getComputedStyle', Y_DOM = Y.DOM, // TODO: how about thead/tbody/tfoot/tr? // TODO: does caption matter? RE_TABLE = /^t(?:able|d|h)$/i, SCROLL_NODE; if (Y.UA.ie) { if (Y.config.doc[COMPAT_MODE] !== 'BackCompat') { SCROLL_NODE = DOCUMENT_ELEMENT; } else { SCROLL_NODE = 'body'; } } Y.mix(Y_DOM, { /** * Returns the inner height of the viewport (exludes scrollbar). * @method winHeight * @return {Number} The current height of the viewport. */ winHeight: function(node) { var h = Y_DOM._getWinSize(node).height; return h; }, /** * Returns the inner width of the viewport (exludes scrollbar). * @method winWidth * @return {Number} The current width of the viewport. */ winWidth: function(node) { var w = Y_DOM._getWinSize(node).width; return w; }, /** * Document height * @method docHeight * @return {Number} The current height of the document. */ docHeight: function(node) { var h = Y_DOM._getDocSize(node).height; return Math.max(h, Y_DOM._getWinSize(node).height); }, /** * Document width * @method docWidth * @return {Number} The current width of the document. */ docWidth: function(node) { var w = Y_DOM._getDocSize(node).width; return Math.max(w, Y_DOM._getWinSize(node).width); }, /** * Amount page has been scroll horizontally * @method docScrollX * @return {Number} The current amount the screen is scrolled horizontally. */ docScrollX: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; // perf optimization var dv = doc.defaultView, pageOffset = (dv) ? dv.pageXOffset : 0; return Math.max(doc[DOCUMENT_ELEMENT].scrollLeft, doc.body.scrollLeft, pageOffset); }, /** * Amount page has been scroll vertically * @method docScrollY * @return {Number} The current amount the screen is scrolled vertically. */ docScrollY: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; // perf optimization var dv = doc.defaultView, pageOffset = (dv) ? dv.pageYOffset : 0; return Math.max(doc[DOCUMENT_ELEMENT].scrollTop, doc.body.scrollTop, pageOffset); }, /** * Gets the current position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getXY * @param element The target element * @return {Array} The XY position of the element TODO: test inDocument/display? */ getXY: function() { if (Y.config.doc[DOCUMENT_ELEMENT][GET_BOUNDING_CLIENT_RECT]) { return function(node) { var xy = null, scrollLeft, scrollTop, mode, box, offX, offY, doc, win, inDoc, rootNode; if (node && node.tagName) { doc = node.ownerDocument; mode = doc[COMPAT_MODE]; if (mode !== _BACK_COMPAT) { rootNode = doc[DOCUMENT_ELEMENT]; } else { rootNode = doc.body; } // inline inDoc check for perf if (rootNode.contains) { inDoc = rootNode.contains(node); } else { inDoc = Y.DOM.contains(rootNode, node); } if (inDoc) { win = doc.defaultView; // inline scroll calc for perf if (win && 'pageXOffset' in win) { scrollLeft = win.pageXOffset; scrollTop = win.pageYOffset; } else { scrollLeft = (SCROLL_NODE) ? doc[SCROLL_NODE].scrollLeft : Y_DOM.docScrollX(node, doc); scrollTop = (SCROLL_NODE) ? doc[SCROLL_NODE].scrollTop : Y_DOM.docScrollY(node, doc); } if (Y.UA.ie) { // IE < 8, quirks, or compatMode if (!doc.documentMode || doc.documentMode < 8 || mode === _BACK_COMPAT) { offX = rootNode.clientLeft; offY = rootNode.clientTop; } } box = node[GET_BOUNDING_CLIENT_RECT](); xy = [box.left, box.top]; if (offX || offY) { xy[0] -= offX; xy[1] -= offY; } if ((scrollTop || scrollLeft)) { if (!Y.UA.ios || (Y.UA.ios >= 4.2)) { xy[0] += scrollLeft; xy[1] += scrollTop; } } } else { xy = Y_DOM._getOffset(node); } } return xy; }; } else { return function(node) { // manually calculate by crawling up offsetParents //Calculate the Top and Left border sizes (assumes pixels) var xy = null, doc, parentNode, bCheck, scrollTop, scrollLeft; if (node) { if (Y_DOM.inDoc(node)) { xy = [node.offsetLeft, node.offsetTop]; doc = node.ownerDocument; parentNode = node; // TODO: refactor with !! or just falsey bCheck = ((Y.UA.gecko || Y.UA.webkit > 519) ? true : false); // TODO: worth refactoring for TOP/LEFT only? while ((parentNode = parentNode.offsetParent)) { xy[0] += parentNode.offsetLeft; xy[1] += parentNode.offsetTop; if (bCheck) { xy = Y_DOM._calcBorders(parentNode, xy); } } // account for any scrolled ancestors if (Y_DOM.getStyle(node, POSITION) != FIXED) { parentNode = node; while ((parentNode = parentNode.parentNode)) { scrollTop = parentNode.scrollTop; scrollLeft = parentNode.scrollLeft; //Firefox does something funky with borders when overflow is not visible. if (Y.UA.gecko && (Y_DOM.getStyle(parentNode, 'overflow') !== 'visible')) { xy = Y_DOM._calcBorders(parentNode, xy); } if (scrollTop || scrollLeft) { xy[0] -= scrollLeft; xy[1] -= scrollTop; } } xy[0] += Y_DOM.docScrollX(node, doc); xy[1] += Y_DOM.docScrollY(node, doc); } else { //Fix FIXED position -- add scrollbars xy[0] += Y_DOM.docScrollX(node, doc); xy[1] += Y_DOM.docScrollY(node, doc); } } else { xy = Y_DOM._getOffset(node); } } return xy; }; } }(),// NOTE: Executing for loadtime branching /** Gets the width of vertical scrollbars on overflowed containers in the body content. @method getScrollbarWidth @return {Number} Pixel width of a scrollbar in the current browser **/ getScrollbarWidth: Y.cached(function () { var doc = Y.config.doc, testNode = doc.createElement('div'), body = doc.getElementsByTagName('body')[0], // 0.1 because cached doesn't support falsy refetch values width = 0.1; if (body) { testNode.style.cssText = "position:absolute;visibility:hidden;overflow:scroll;width:20px;"; testNode.appendChild(doc.createElement('p')).style.height = '1px'; body.insertBefore(testNode, body.firstChild); width = testNode.offsetWidth - testNode.clientWidth; body.removeChild(testNode); } return width; }, null, 0.1), /** * Gets the current X position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getX * @param element The target element * @return {Number} The X position of the element */ getX: function(node) { return Y_DOM.getXY(node)[0]; }, /** * Gets the current Y position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getY * @param element The target element * @return {Number} The Y position of the element */ getY: function(node) { return Y_DOM.getXY(node)[1]; }, /** * Set the position of an html element in page coordinates. * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setXY * @param element The target element * @param {Array} xy Contains X & Y values for new position (coordinates are page-based) * @param {Boolean} noRetry By default we try and set the position a second time if the first fails */ setXY: function(node, xy, noRetry) { var setStyle = Y_DOM.setStyle, pos, delta, newXY, currentXY; if (node && xy) { pos = Y_DOM.getStyle(node, POSITION); delta = Y_DOM._getOffset(node); if (pos == 'static') { // default to relative pos = RELATIVE; setStyle(node, POSITION, pos); } currentXY = Y_DOM.getXY(node); if (xy[0] !== null) { setStyle(node, LEFT, xy[0] - currentXY[0] + delta[0] + 'px'); } if (xy[1] !== null) { setStyle(node, TOP, xy[1] - currentXY[1] + delta[1] + 'px'); } if (!noRetry) { newXY = Y_DOM.getXY(node); if (newXY[0] !== xy[0] || newXY[1] !== xy[1]) { Y_DOM.setXY(node, xy, true); } } } else { } }, /** * Set the X position of an html element in page coordinates, regardless of how the element is positioned. * The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setX * @param element The target element * @param {Number} x The X values for new position (coordinates are page-based) */ setX: function(node, x) { return Y_DOM.setXY(node, [x, null]); }, /** * Set the Y position of an html element in page coordinates, regardless of how the element is positioned. * The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setY * @param element The target element * @param {Number} y The Y values for new position (coordinates are page-based) */ setY: function(node, y) { return Y_DOM.setXY(node, [null, y]); }, /** * @method swapXY * @description Swap the xy position with another node * @param {Node} node The node to swap with * @param {Node} otherNode The other node to swap with * @return {Node} */ swapXY: function(node, otherNode) { var xy = Y_DOM.getXY(node); Y_DOM.setXY(node, Y_DOM.getXY(otherNode)); Y_DOM.setXY(otherNode, xy); }, _calcBorders: function(node, xy2) { var t = parseInt(Y_DOM[GET_COMPUTED_STYLE](node, BORDER_TOP_WIDTH), 10) || 0, l = parseInt(Y_DOM[GET_COMPUTED_STYLE](node, BORDER_LEFT_WIDTH), 10) || 0; if (Y.UA.gecko) { if (RE_TABLE.test(node.tagName)) { t = 0; l = 0; } } xy2[0] += l; xy2[1] += t; return xy2; }, _getWinSize: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; var win = doc.defaultView || doc.parentWindow, mode = doc[COMPAT_MODE], h = win.innerHeight, w = win.innerWidth, root = doc[DOCUMENT_ELEMENT]; if ( mode && !Y.UA.opera ) { // IE, Gecko if (mode != 'CSS1Compat') { // Quirks root = doc.body; } h = root.clientHeight; w = root.clientWidth; } return { height: h, width: w }; }, _getDocSize: function(node) { var doc = (node) ? Y_DOM._getDoc(node) : Y.config.doc, root = doc[DOCUMENT_ELEMENT]; if (doc[COMPAT_MODE] != 'CSS1Compat') { root = doc.body; } return { height: root.scrollHeight, width: root.scrollWidth }; } }); })(Y); (function(Y) { var TOP = 'top', RIGHT = 'right', BOTTOM = 'bottom', LEFT = 'left', getOffsets = function(r1, r2) { var t = Math.max(r1[TOP], r2[TOP]), r = Math.min(r1[RIGHT], r2[RIGHT]), b = Math.min(r1[BOTTOM], r2[BOTTOM]), l = Math.max(r1[LEFT], r2[LEFT]), ret = {}; ret[TOP] = t; ret[RIGHT] = r; ret[BOTTOM] = b; ret[LEFT] = l; return ret; }, DOM = Y.DOM; Y.mix(DOM, { /** * Returns an Object literal containing the following about this element: (top, right, bottom, left) * @for DOM * @method region * @param {HTMLElement} element The DOM element. * @return {Object} Object literal containing the following about this element: (top, right, bottom, left) */ region: function(node) { var xy = DOM.getXY(node), ret = false; if (node && xy) { ret = DOM._getRegion( xy[1], // top xy[0] + node.offsetWidth, // right xy[1] + node.offsetHeight, // bottom xy[0] // left ); } return ret; }, /** * Find the intersect information for the passed nodes. * @method intersect * @for DOM * @param {HTMLElement} element The first element * @param {HTMLElement | Object} element2 The element or region to check the interect with * @param {Object} altRegion An object literal containing the region for the first element if we already have the data (for performance e.g. DragDrop) * @return {Object} Object literal containing the following intersection data: (top, right, bottom, left, area, yoff, xoff, inRegion) */ intersect: function(node, node2, altRegion) { var r = altRegion || DOM.region(node), region = {}, n = node2, off; if (n.tagName) { region = DOM.region(n); } else if (Y.Lang.isObject(node2)) { region = node2; } else { return false; } off = getOffsets(region, r); return { top: off[TOP], right: off[RIGHT], bottom: off[BOTTOM], left: off[LEFT], area: ((off[BOTTOM] - off[TOP]) * (off[RIGHT] - off[LEFT])), yoff: ((off[BOTTOM] - off[TOP])), xoff: (off[RIGHT] - off[LEFT]), inRegion: DOM.inRegion(node, node2, false, altRegion) }; }, /** * Check if any part of this node is in the passed region * @method inRegion * @for DOM * @param {Object} node The node to get the region from * @param {Object} node2 The second node to get the region from or an Object literal of the region * @param {Boolean} all Should all of the node be inside the region * @param {Object} altRegion An object literal containing the region for this node if we already have the data (for performance e.g. DragDrop) * @return {Boolean} True if in region, false if not. */ inRegion: function(node, node2, all, altRegion) { var region = {}, r = altRegion || DOM.region(node), n = node2, off; if (n.tagName) { region = DOM.region(n); } else if (Y.Lang.isObject(node2)) { region = node2; } else { return false; } if (all) { return ( r[LEFT] >= region[LEFT] && r[RIGHT] <= region[RIGHT] && r[TOP] >= region[TOP] && r[BOTTOM] <= region[BOTTOM] ); } else { off = getOffsets(region, r); if (off[BOTTOM] >= off[TOP] && off[RIGHT] >= off[LEFT]) { return true; } else { return false; } } }, /** * Check if any part of this element is in the viewport * @method inViewportRegion * @for DOM * @param {HTMLElement} element The DOM element. * @param {Boolean} all Should all of the node be inside the region * @param {Object} altRegion An object literal containing the region for this node if we already have the data (for performance e.g. DragDrop) * @return {Boolean} True if in region, false if not. */ inViewportRegion: function(node, all, altRegion) { return DOM.inRegion(node, DOM.viewportRegion(node), all, altRegion); }, _getRegion: function(t, r, b, l) { var region = {}; region[TOP] = region[1] = t; region[LEFT] = region[0] = l; region[BOTTOM] = b; region[RIGHT] = r; region.width = region[RIGHT] - region[LEFT]; region.height = region[BOTTOM] - region[TOP]; return region; }, /** * Returns an Object literal containing the following about the visible region of viewport: (top, right, bottom, left) * @method viewportRegion * @for DOM * @return {Object} Object literal containing the following about the visible region of the viewport: (top, right, bottom, left) */ viewportRegion: function(node) { node = node || Y.config.doc.documentElement; var ret = false, scrollX, scrollY; if (node) { scrollX = DOM.docScrollX(node); scrollY = DOM.docScrollY(node); ret = DOM._getRegion(scrollY, // top DOM.winWidth(node) + scrollX, // right scrollY + DOM.winHeight(node), // bottom scrollX); // left } return ret; } }); })(Y); }, '@VERSION@', {"requires": ["dom-base", "dom-style"]}); YUI.add('selector-native', function (Y, NAME) { (function(Y) { /** * The selector-native module provides support for native querySelector * @module dom * @submodule selector-native * @for Selector */ /** * Provides support for using CSS selectors to query the DOM * @class Selector * @static * @for Selector */ Y.namespace('Selector'); // allow native module to standalone var COMPARE_DOCUMENT_POSITION = 'compareDocumentPosition', OWNER_DOCUMENT = 'ownerDocument'; var Selector = { _types: { esc: { token: '\uE000', re: /\\[:\[\]\(\)#\.\'\>+~"]/gi }, attr: { token: '\uE001', re: /(\[[^\]]*\])/g }, pseudo: { token: '\uE002', re: /(\([^\)]*\))/g } }, useNative: true, _escapeId: function(id) { if (id) { id = id.replace(/([:\[\]\(\)#\.'<>+~"])/g,'\\$1'); } return id; }, _compare: ('sourceIndex' in Y.config.doc.documentElement) ? function(nodeA, nodeB) { var a = nodeA.sourceIndex, b = nodeB.sourceIndex; if (a === b) { return 0; } else if (a > b) { return 1; } return -1; } : (Y.config.doc.documentElement[COMPARE_DOCUMENT_POSITION] ? function(nodeA, nodeB) { if (nodeA[COMPARE_DOCUMENT_POSITION](nodeB) & 4) { return -1; } else { return 1; } } : function(nodeA, nodeB) { var rangeA, rangeB, compare; if (nodeA && nodeB) { rangeA = nodeA[OWNER_DOCUMENT].createRange(); rangeA.setStart(nodeA, 0); rangeB = nodeB[OWNER_DOCUMENT].createRange(); rangeB.setStart(nodeB, 0); compare = rangeA.compareBoundaryPoints(1, rangeB); // 1 === Range.START_TO_END } return compare; }), _sort: function(nodes) { if (nodes) { nodes = Y.Array(nodes, 0, true); if (nodes.sort) { nodes.sort(Selector._compare); } } return nodes; }, _deDupe: function(nodes) { var ret = [], i, node; for (i = 0; (node = nodes[i++]);) { if (!node._found) { ret[ret.length] = node; node._found = true; } } for (i = 0; (node = ret[i++]);) { node._found = null; node.removeAttribute('_found'); } return ret; }, /** * Retrieves a set of nodes based on a given CSS selector. * @method query * * @param {string} selector The CSS Selector to test the node against. * @param {HTMLElement} root optional An HTMLElement to start the query from. Defaults to Y.config.doc * @param {Boolean} firstOnly optional Whether or not to return only the first match. * @return {Array} An array of nodes that match the given selector. * @static */ query: function(selector, root, firstOnly, skipNative) { root = root || Y.config.doc; var ret = [], useNative = (Y.Selector.useNative && Y.config.doc.querySelector && !skipNative), queries = [[selector, root]], query, result, i, fn = (useNative) ? Y.Selector._nativeQuery : Y.Selector._bruteQuery; if (selector && fn) { // split group into seperate queries if (!skipNative && // already done if skipping (!useNative || root.tagName)) { // split native when element scoping is needed queries = Selector._splitQueries(selector, root); } for (i = 0; (query = queries[i++]);) { result = fn(query[0], query[1], firstOnly); if (!firstOnly) { // coerce DOM Collection to Array result = Y.Array(result, 0, true); } if (result) { ret = ret.concat(result); } } if (queries.length > 1) { // remove dupes and sort by doc order ret = Selector._sort(Selector._deDupe(ret)); } } return (firstOnly) ? (ret[0] || null) : ret; }, _replaceSelector: function(selector) { var esc = Y.Selector._parse('esc', selector), // pull escaped colon, brackets, etc. attrs, pseudos; // first replace escaped chars, which could be present in attrs or pseudos selector = Y.Selector._replace('esc', selector); // then replace pseudos before attrs to avoid replacing :not([foo]) pseudos = Y.Selector._parse('pseudo', selector); selector = Selector._replace('pseudo', selector); attrs = Y.Selector._parse('attr', selector); selector = Y.Selector._replace('attr', selector); return { esc: esc, attrs: attrs, pseudos: pseudos, selector: selector }; }, _restoreSelector: function(replaced) { var selector = replaced.selector; selector = Y.Selector._restore('attr', selector, replaced.attrs); selector = Y.Selector._restore('pseudo', selector, replaced.pseudos); selector = Y.Selector._restore('esc', selector, replaced.esc); return selector; }, _replaceCommas: function(selector) { var replaced = Y.Selector._replaceSelector(selector), selector = replaced.selector; if (selector) { selector = selector.replace(/,/g, '\uE007'); replaced.selector = selector; selector = Y.Selector._restoreSelector(replaced); } return selector; }, // allows element scoped queries to begin with combinator // e.g. query('> p', document.body) === query('body > p') _splitQueries: function(selector, node) { if (selector.indexOf(',') > -1) { selector = Y.Selector._replaceCommas(selector); } var groups = selector.split('\uE007'), // split on replaced comma token queries = [], prefix = '', id, i, len; if (node) { // enforce for element scoping if (node.nodeType === 1) { // Elements only id = Y.Selector._escapeId(Y.DOM.getId(node)); if (!id) { id = Y.guid(); Y.DOM.setId(node, id); } prefix = '[id="' + id + '"] '; } for (i = 0, len = groups.length; i < len; ++i) { selector = prefix + groups[i]; queries.push([selector, node]); } } return queries; }, _nativeQuery: function(selector, root, one) { if (Y.UA.webkit && selector.indexOf(':checked') > -1 && (Y.Selector.pseudos && Y.Selector.pseudos.checked)) { // webkit (chrome, safari) fails to pick up "selected" with "checked" return Y.Selector.query(selector, root, one, true); // redo with skipNative true to try brute query } try { return root['querySelector' + (one ? '' : 'All')](selector); } catch(e) { // fallback to brute if available return Y.Selector.query(selector, root, one, true); // redo with skipNative true } }, filter: function(nodes, selector) { var ret = [], i, node; if (nodes && selector) { for (i = 0; (node = nodes[i++]);) { if (Y.Selector.test(node, selector)) { ret[ret.length] = node; } } } else { } return ret; }, test: function(node, selector, root) { var ret = false, useFrag = false, groups, parent, item, items, frag, id, i, j, group; if (node && node.tagName) { // only test HTMLElements if (typeof selector == 'function') { // test with function ret = selector.call(node, node); } else { // test with query // we need a root if off-doc groups = selector.split(','); if (!root && !Y.DOM.inDoc(node)) { parent = node.parentNode; if (parent) { root = parent; } else { // only use frag when no parent to query frag = node[OWNER_DOCUMENT].createDocumentFragment(); frag.appendChild(node); root = frag; useFrag = true; } } root = root || node[OWNER_DOCUMENT]; id = Y.Selector._escapeId(Y.DOM.getId(node)); if (!id) { id = Y.guid(); Y.DOM.setId(node, id); } for (i = 0; (group = groups[i++]);) { // TODO: off-dom test group += '[id="' + id + '"]'; items = Y.Selector.query(group, root); for (j = 0; item = items[j++];) { if (item === node) { ret = true; break; } } if (ret) { break; } } if (useFrag) { // cleanup frag.removeChild(node); } }; } return ret; }, /** * A convenience function to emulate Y.Node's aNode.ancestor(selector). * @param {HTMLElement} element An HTMLElement to start the query from. * @param {String} selector The CSS selector to test the node against. * @return {HTMLElement} The ancestor node matching the selector, or null. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @static * @method ancestor */ ancestor: function (element, selector, testSelf) { return Y.DOM.ancestor(element, function(n) { return Y.Selector.test(n, selector); }, testSelf); }, _parse: function(name, selector) { return selector.match(Y.Selector._types[name].re); }, _replace: function(name, selector) { var o = Y.Selector._types[name]; return selector.replace(o.re, o.token); }, _restore: function(name, selector, items) { if (items) { var token = Y.Selector._types[name].token, i, len; for (i = 0, len = items.length; i < len; ++i) { selector = selector.replace(token, items[i]); } } return selector; } }; Y.mix(Y.Selector, Selector, true); })(Y); }, '@VERSION@', {"requires": ["dom-base"]}); YUI.add('selector', function (Y, NAME) { }, '@VERSION@', {"requires": ["selector-native"]}); YUI.add('event-custom-base', function (Y, NAME) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var DO_BEFORE = 0, DO_AFTER = 1, DO = { /** * Cache of objects touched by the utility * @property objs * @static * @deprecated Since 3.6.0. The `_yuiaop` property on the AOP'd object * replaces the role of this property, but is considered to be private, and * is only mentioned to provide a migration path. * * If you have a use case which warrants migration to the _yuiaop property, * please file a ticket to let us know what it's used for and we can see if * we need to expose hooks for that functionality more formally. */ objs: null, /** * <p>Execute the supplied method before the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt> * <dd>Replace the arguments that the original function will be * called with.</dd> * <dt></code>Y.Do.Prevent(message)</code></dt> * <dd>Don't execute the wrapped function. Other before phase * wrappers will be executed.</dd> * </dl> * * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {string} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_BEFORE, f, obj, sFn); }, /** * <p>Execute the supplied method after the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt> * <dd>Return <code>returnValue</code> instead of the wrapped * method's original return value. This can be further altered by * other after phase wrappers.</dd> * </dl> * * <p>The static properties <code>Y.Do.originalRetVal</code> and * <code>Y.Do.currentRetVal</code> will be populated for reference.</p> * * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return {string} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_AFTER, f, obj, sFn); }, /** * Execute the supplied method before or after the specified function. * Used by <code>before</code> and <code>after</code>. * * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (!obj._yuiaop) { // create a map entry for the obj if it doesn't exist, to hold overridden methods obj._yuiaop = {}; } o = obj._yuiaop; if (!o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription. * * @method detach * @param handle {string} the subscription handle * @static */ detach: function(handle) { if (handle.detach) { handle.detach(); } } }; Y.Do = DO; ////////////////////////////////////////////////////////////////////////// /** * Contains the return value from the wrapped method, accessible * by 'after' event listeners. * * @property originalRetVal * @static * @since 3.2.0 */ /** * Contains the current state of the return value, consumable by * 'after' event listeners, and updated if an after subscriber * changes the return value generated by the wrapped function. * * @property currentRetVal * @static * @since 3.2.0 */ ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ DO.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype._delete = function (sid) { delete this.before[sid]; delete this.after[sid]; }; /** * <p>Execute the wrapped method. All arguments are passed into the wrapping * functions. If any of the before wrappers return an instance of * <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped * function nor any after phase subscribers will be executed.</p> * * <p>The return value will be the return value of the wrapped function or one * provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or * <code>Y.Do.AlterReturn</code>. * * @method exec * @param arg* {any} Arguments are passed to the wrapping and wrapped functions * @return {any} Return value of wrapped function unless overwritten (see above) */ DO.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case DO.Halt: return ret.retVal; case DO.AlterArgs: args = ret.newArgs; break; case DO.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } DO.originalRetVal = ret; DO.currentRetVal = ret; // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor === DO.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor === DO.AlterReturn) { ret = newRet.newRetVal; // Update the static retval state DO.currentRetVal = ret; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. Useful for Do.before subscribers. An * example would be a service that scrubs out illegal characters prior to * executing the core business logic. * @class Do.AlterArgs * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newArgs {Array} Call parameters to be used for the original method * instead of the arguments originally passed in. */ DO.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller. Useful for Do.after subscribers. * @class Do.AlterReturn * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newRetVal {any} Return value passed to code that invoked the wrapped * function. */ DO.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. Useful for Do.before subscribers. * @class Do.Halt * @constructor * @param msg {String} (optional) Explanation of why the termination was done * @param retVal {any} Return value passed to code that invoked the wrapped * function. */ DO.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute. Useful * for Do.before subscribers. * @class Do.Prevent * @constructor * @param msg {String} (optional) Explanation of why the termination was done */ DO.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param retVal {any} Return value passed to code that invoked the wrapped * function. * @deprecated use Y.Do.Halt or Y.Do.Prevent */ DO.Error = DO.Halt; ////////////////////////////////////////////////////////////////////////// /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ // var onsubscribeType = "_event:onsub", var YArray = Y.Array, AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], CONFIGS_HASH = YArray.hash(CONFIGS), nativeSlice = Array.prototype.slice, YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log', mixConfigs = function(r, s, ov) { var p; for (p in s) { if (CONFIGS_HASH[p] && (ov || !(p in r))) { r[p] = s[p]; } } return r; }; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires. * @param {object} defaults configuration object. * @class CustomEvent * @constructor */ /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ Y.CustomEvent = function(type, defaults) { this._kds = Y.CustomEvent.keepDeprecatedSubs; this.id = Y.guid(); this.type = type; this.silent = this.logSystem = (type === YUI_LOG); if (this._kds) { /** * The subscribers to this event * @property subscribers * @type Subscriber {} * @deprecated */ /** * 'After' subscribers * @property afters * @type Subscriber {} * @deprecated */ this.subscribers = {}; this.afters = {}; } if (defaults) { mixConfigs(this, defaults, true); } }; /** * Static flag to enable population of the <a href="#property_subscribers">`subscribers`</a> * and <a href="#property_subscribers">`afters`</a> properties held on a `CustomEvent` instance. * * These properties were changed to private properties (`_subscribers` and `_afters`), and * converted from objects to arrays for performance reasons. * * Setting this property to true will populate the deprecated `subscribers` and `afters` * properties for people who may be using them (which is expected to be rare). There will * be a performance hit, compared to the new array based implementation. * * If you are using these deprecated properties for a use case which the public API * does not support, please file an enhancement request, and we can provide an alternate * public implementation which doesn't have the performance cost required to maintiain the * properties as objects. * * @property keepDeprecatedSubs * @static * @for CustomEvent * @type boolean * @default false * @deprecated */ Y.CustomEvent.keepDeprecatedSubs = false; Y.CustomEvent.mixConfigs = mixConfigs; Y.CustomEvent.prototype = { constructor: Y.CustomEvent, /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ /** * This event has fired if true * * @property fired * @type boolean * @default false; */ /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default false */ /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ /** * The subscribers to this event * @property _subscribers * @type Subscriber [] * @private */ /** * 'After' subscribers * @property _afters * @type Subscriber [] * @private */ /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ signature : YUI3_SIGNATURE, /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ context : Y, /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ preventable : true, /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ bubbles : true, /** * Returns the number of subscribers for this event as the sum of the on() * subscribers and after() subscribers. * * @method hasSubs * @return Number */ hasSubs: function(when) { var s = 0, a = 0, subs = this._subscribers, afters = this._afters, sib = this.sibling; if (subs) { s = subs.length; } if (afters) { a = afters.length; } if (sib) { subs = sib._subscribers; afters = sib._afters; if (subs) { s += subs.length; } if (afters) { a += afters.length; } } if (when) { return (when === 'after') ? a : s; } return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { this.monitored = true; var type = this.id + '|' + this.type + '_' + what, args = nativeSlice.call(arguments, 0); args[0] = type; return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @method getSubs * @return {Array} first item is the on subscribers, second the after. */ getSubs: function() { var sibling = this.sibling, subs = this._subscribers, afters = this._afters, siblingSubs, siblingAfters; if (sibling) { siblingSubs = sibling._subscribers; siblingAfters = sibling._afters; } if (siblingSubs) { if (subs) { subs = subs.concat(siblingSubs); } else { subs = siblingSubs.concat(); } } else { if (subs) { subs = subs.concat(); } else { subs = []; } } if (siblingAfters) { if (afters) { afters = afters.concat(siblingAfters); } else { afters = siblingAfters.concat(); } } else { if (afters) { afters = afters.concat(); } else { afters = []; } } return [subs, afters]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply. * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { mixConfigs(this, o, force); }, /** * Create the Subscription for subscribing function, context, and bound * arguments. If this is a fireOnce event, the subscriber is immediately * notified. * * @method _on * @param fn {Function} Subscription callback * @param [context] {Object} Override `this` in the callback * @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire() * @param [when] {String} "after" to slot into after subscribers * @return {EventHandle} * @protected */ _on: function(fn, context, args, when) { if (!fn) { this.log('Invalid callback for CE: ' + this.type); } var s = new Y.Subscriber(fn, context, args, when); if (this.fireOnce && this.fired) { if (this.async) { setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0); } else { this._notify(s, this.firedWith); } } if (when === AFTER) { if (!this._afters) { this._afters = []; this._hasAfters = true; } this._afters.push(s); } else { if (!this._subscribers) { this._subscribers = []; this._hasSubs = true; } this._subscribers.push(s); } if (this._kds) { if (when === AFTER) { this.afters[s.id] = s; } else { this.subscribers[s.id] = s; } } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute. * @return {EventHandle} Unsubscribe handle. * @deprecated use on. */ subscribe: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} An object with a detach method to detch the handler(s). */ on: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; if (this.monitored && this.host) { this.host._monitor('attach', this, { args: arguments }); } return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle Unsubscribe handle. */ after: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int} returns the number of subscribers unsubscribed. */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var i, s, found = 0, subs = this._subscribers, afters = this._afters; if (subs) { for (i = subs.length; i >= 0; i--) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, subs, i); found++; } } } if (afters) { for (i = afters.length; i >= 0; i--) { s = afters[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, afters, i); found++; } } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed. * @deprecated use detach. */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param {Subscriber} s the subscriber. * @param {Array} args the arguments array to apply to the listener. * @protected */ _notify: function(s, args, ef) { this.log(this.type + '->' + 'sub: ' + s.id); var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { this.log(this.type + ' cancelled by subscriber'); return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param {string} msg message to log. * @param {string} cat log category. */ log: function(msg, cat) { }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise. * */ fire: function() { // push is the fastest way to go from arguments to arrays // for most browsers currently // http://jsperf.com/push-vs-concat-vs-slice/2 var args = []; args.push.apply(args, arguments); return this._fire(args); }, /** * Private internal implementation for `fire`, which is can be used directly by * `EventTarget` and other event module classes which have already converted from * an `arguments` list to an array, to avoid the repeated overhead. * * @method _fire * @private * @param {Array} args The array of arguments passed to be passed to handlers. * @return {boolean} false if one of the subscribers returned false, true otherwise. */ _fire: function(args) { if (this.fireOnce && this.fired) { this.log('fireOnce event: ' + this.type + ' already fired'); return true; } else { // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; if (this.fireOnce) { this.firedWith = args; } if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, /** * Set up for notifying subscribers of non-emitFacade events. * * @method fireSimple * @param args {Array} Arguments passed to fire() * @return Boolean false if a subscriber returned false * @protected */ fireSimple: function(args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } if (this.broadcast) { this._broadcast(args); } return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { this.log('Missing event-custom-complex needed to emit a facade for: ' + this.type); args[0] = args[0] || {}; return this.fireSimple(args); }, /** * Notifies a list of subscribers. * * @method _procSubs * @param subs {Array} List of subscribers * @param args {Array} Arguments passed to fire() * @param ef {} * @return Boolean false if a subscriber returns false or stops the event * propagation via e.stopPropagation(), * e.stopImmediatePropagation(), or e.halt() * @private */ _procSubs: function(subs, args, ef) { var s, i, l; for (i = 0, l = subs.length; i < l; i++) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped === 2) { return false; } } } return true; }, /** * Notifies the YUI instance if the event is configured with broadcast = 1, * and both the YUI instance and Y.Global if configured with broadcast = 2. * * @method _broadcast * @param args {Array} Arguments sent to fire() * @private */ _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = args.concat(); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast === 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed. * @deprecated use detachAll. */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {int} The number of listeners unsubscribed. */ detachAll: function() { return this.detach(); }, /** * Deletes the subscriber from the internal store of on() and after() * subscribers. * * @method _delete * @param s subscriber object. * @param subs (optional) on or after subscriber array * @param index (optional) The index found. * @private */ _delete: function(s, subs, i) { var when = s._when; if (!subs) { subs = (when === AFTER) ? this._afters : this._subscribers; i = YArray.indexOf(subs, s, 0); } if (subs) { if (s && subs[i] === s) { subs.splice(i, 1); if (subs.length === 0) { if (when === AFTER) { this._hasAfters = false; } else { this._hasSubs = false; } } } } if (this._kds) { if (when === AFTER) { delete this.afters[s.id]; } else { delete this.subscribers[s.id]; } } if (this.monitored && this.host) { this.host._monitor('detach', this, { ce: this, sub: s }); } if (s) { s.deleted = true; } } }; /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute. * @param {Object} context The value of the keyword 'this' in the listener. * @param {Array} args* 0..n additional arguments to supply the listener. * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args, when) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.guid(); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; this._when = when; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; Y.Subscriber.prototype = { constructor: Y.Subscriber, _notify: function(c, args, ce) { if (this.deleted && !this.postponed) { if (this.postponed) { delete this.fn; delete this.context; } else { delete this.postponed; return null; } } var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } if (this.once) { ce._delete(this); } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber. * @param ce {CustomEvent} The custom event that sent the notification. */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config && Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch (e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute. * @param {Object} context optional 'this' keyword for the listener. * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn === fn) && this.context === context); } else { return (this.fn === fn); } }, valueOf : function() { return this.id; } }; /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param {CustomEvent} evt the custom event. * @param {Subscriber} sub the subscriber. */ Y.EventHandle = function(evt, sub) { /** * The custom event * * @property evt * @type CustomEvent */ this.evt = evt; /** * The subscriber object * * @property sub * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { batch: function(f, c) { f.call(c || this, this); if (Y.Lang.isArray(this.evt)) { Y.Array.each(this.evt, function(h) { h.batch.call(c || h, f); }); } }, /** * Detaches this subscriber * @method detach * @return {int} the number of detached listeners */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { if (Y.Lang.isArray(evt)) { for (i = 0; i < evt.length; i++) { detached += evt[i].detach(); } } else { evt._delete(this.sub); detached = 1; } } return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { return this.evt.monitor.apply(this.evt, arguments); } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {String} the prefix to apply to non-prefixed event names */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', WILD_TYPE_RE = /(.*?)(:)(.*?)/, _wildType = Y.cached(function(type) { return type.replace(WILD_TYPE_RE, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = function(type, pre) { if (!pre || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }, /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t === '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { var etState = this._yuievt, etConfig; if (!etState) { etState = this._yuievt = { events: {}, // PERF: Not much point instantiating lazily. We're bound to have events targets: null, // PERF: Instantiate lazily, if user actually adds target, config: { host: this, context: this }, chain: Y.config.chain }; } etConfig = etState.config; if (opts) { mixConfigs(etConfig, opts, true); if (opts.chain !== undefined) { etState.chain = opts.chain; } if (opts.prefix) { etConfig.prefix = opts.prefix; } } }; ET.prototype = { constructor: ET, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ once: function() { var handle = this.on.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>after</code> except the * listener is immediatelly detached when it is executed. * @method onceAfter * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ onceAfter: function() { var handle = this.after.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Takes the type parameter passed to 'on' and parses out the * various pieces that could be included in the type. If the * event type is passed without a prefix, it will be expanded * to include the prefix one is supplied or the event target * is configured with a default prefix. * @method parseType * @param {String} type the type * @param {String} [pre=this._yuievt.config.prefix] the prefix * @since 3.3.0 * @return {Array} an array containing: * * the detach category, if supplied, * * the prefixed event type, * * whether or not this is an after listener, * * the supplied event type */ parseType: function(type, pre) { return _parseType(type, pre || this._yuievt.config.prefix); }, /** * Subscribe a callback function to a custom event fired by this object or * from an object that bubbles its events to this object. * * Callback functions for events published with `emitFacade = true` will * receive an `EventFacade` as the first argument (typically named "e"). * These callbacks can then call `e.preventDefault()` to disable the * behavior published to that event's `defaultFn`. See the `EventFacade` * API for all available properties and methods. Subscribers to * non-`emitFacade` events will receive the arguments passed to `fire()` * after the event name. * * To subscribe to multiple events at once, pass an object as the first * argument, where the key:value pairs correspond to the eventName:callback, * or pass an array of event names as the first argument to subscribe to * all listed events with the same callback. * * Returning `false` from a callback is supported as an alternative to * calling `e.preventDefault(); e.stopPropagation();`. However, it is * recommended to use the event methods whenever possible. * * @method on * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ on: function(type, fn, context) { var yuievt = this._yuievt, parts = _parseType(type, yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = nativeSlice.call(arguments, 0); ret = []; if (L.isArray(type)) { isArr = true; } after = type._after; delete type._after; Y.each(type, function(v, k) { if (L.isObject(v)) { f = v.fn || ((L.isFunction(v)) ? v : f); c = v.context || c; } var nv = (after) ? AFTER_PREFIX : ''; args[0] = nv + ((isArr) ? v : k); args[1] = f; args[2] = c; ret.push(this.on.apply(this, args)); }, this); return (yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) { args = nativeSlice.call(arguments, 0); args.splice(2, 0, Node.getDOMNode(this)); return Y.on.apply(Y, args); } type = parts[1]; if (Y.instanceOf(this, YUI)) { adapt = Y.Env.evt.plugins[type]; args = nativeSlice.call(arguments, 0); args[0] = shorttype; if (Node) { n = args[2]; if (Y.instanceOf(n, Y.NodeList)) { n = Y.NodeList.getDOMNodes(n); } else if (Y.instanceOf(n, Node)) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? nativeSlice.call(arguments, 3) : null, (after) ? 'after' : true); // TODO: More robust regex, accounting for category if (type.indexOf("*:") !== -1) { this._hasSiblings = true; } } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node)); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return this; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, adapt, store = Y.Env.evt.handles, detachhost, cat, args, ce, keyDetacher = function(lcat, ltype, host) { var handles = lcat[ltype], ce, i; if (handles) { for (i = handles.length - 1; i >= 0; --i) { ce = handles[i].evt; if (ce.host === host || ce.el === host) { handles[i].detach(); } } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; detachhost = (isNode) ? Y.Node.getDOMNode(this) : this; if (cat) { if (type) { keyDetacher(cat, type, detachhost); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i, detachhost); } } } return this; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { type.detach(); return this; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = nativeSlice.call(arguments, 0); args[2] = Node.getDOMNode(this); Y.detach.apply(Y, args); return this; } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (Y.instanceOf(this, YUI)) { args = nativeSlice.call(arguments, 0); // use the adaptor specific detach code if if (adapt && adapt.detach) { adapt.detach.apply(Y, args); return this; // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; Y.Event.detach.apply(Y.Event, args); return this; } } // ce = evts[type]; ce = evts[parts[1]]; if (ce) { ce.detach(fn, context); } return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {String} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {String} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {String} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'async': fireOnce event listeners will fire synchronously if the event has already * fired unless async is true. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { var ret, etState = this._yuievt, etConfig = etState.config, pre = etConfig.prefix; if (typeof type === "string") { if (pre) { type = _getType(type, pre); } ret = this._publish(type, etConfig, opts); } else { ret = {}; Y.each(type, function(v, k) { if (pre) { k = _getType(k, pre); } ret[k] = this._publish(k, etConfig, v || opts); }, this); } return ret; }, /** * Returns the fully qualified type, given a short type string. * That is, returns "foo:bar" when given "bar" if "foo" is the configured prefix. * * NOTE: This method, unlike _getType, does no checking of the value passed in, and * is designed to be used with the low level _publish() method, for critical path * implementations which need to fast-track publish for performance reasons. * * @method _getFullType * @private * @param {String} type The short type to prefix * @return {String} The prefixed type, if a prefix is set, otherwise the type passed in */ _getFullType : function(type) { var pre = this._yuievt.config.prefix; if (pre) { return pre + PREFIX_DELIMITER + type; } else { return type; } }, /** * The low level event publish implementation. It expects all the massaging to have been done * outside of this method. e.g. the `type` to `fullType` conversion. It's designed to be a fast * path publish, which can be used by critical code paths to improve performance. * * @method _publish * @private * @param {String} fullType The prefixed type of the event to publish. * @param {Object} etOpts The EventTarget specific configuration to mix into the published event. * @param {Object} ceOpts The publish specific configuration to mix into the published event. * @return {CustomEvent} The published event. If called without `etOpts` or `ceOpts`, this will * be the default `CustomEvent` instance, and can be configured independently. */ _publish : function(fullType, etOpts, ceOpts) { var ce, etState = this._yuievt, etConfig = etState.config, host = etConfig.host, context = etConfig.context, events = etState.events; ce = events[fullType]; // PERF: Hate to pull the check out of monitor, but trying to keep critical path tight. if ((etConfig.monitored && !ce) || (ce && ce.monitored)) { this._monitor('publish', fullType, { args: arguments }); } if (!ce) { // Publish event ce = events[fullType] = new Y.CustomEvent(fullType, etOpts); if (!etOpts) { ce.host = host; ce.context = context; } } if (ceOpts) { mixConfigs(ce, ceOpts, true); } return ce; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', 'fire', and 'publish'. * When configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @method _monitor * @param what {String} 'attach', 'detach', 'fire', or 'publish' * @param eventType {String|CustomEvent} The prefixed name of the event being monitored, or the CustomEvent object. * @param o {Object} Information about the event interaction, such as * fire() args, subscription category, publish config * @private */ _monitor: function(what, eventType, o) { var monitorevt, ce, type; if (eventType) { if (typeof eventType === "string") { type = eventType; ce = this.getEvent(eventType, true); } else { ce = eventType; type = eventType.type; } if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { monitorevt = type + '_' + what; o.monitored = what; this.fire.call(this, monitorevt, o); } } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {EventTarget} the event host */ fire: function(type) { var typeIncluded = (typeof type === "string"), argCount = arguments.length, t = type, yuievt = this._yuievt, etConfig = yuievt.config, pre = etConfig.prefix, ret, ce, ce2, args; if (typeIncluded && argCount <= 2) { // PERF: Try to avoid slice/iteration for the common signatures if (argCount === 2) { args = [arguments[1]]; // fire("foo", {}) } else { args = []; // fire("foo") } } else { args = nativeSlice.call(arguments, ((typeIncluded) ? 1 : 0)); } if (!typeIncluded) { t = (type && type.type); } if (pre) { t = _getType(t, pre); } ce = yuievt.events[t]; if (this._hasSiblings) { ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } } // PERF: trying to avoid function call, since this is a critical path if ((etConfig.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { this._monitor('fire', (ce || t), { args: args }); } // this event has not been published or subscribed to if (!ce) { if (yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { if (ce2) { ce.sibling = ce2; } ret = ce._fire(args); } return (yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { var ce2; // delegate to *:type events if there are subscribers if (type.indexOf(PREFIX_DELIMITER) > -1) { type = _wildType(type); ce2 = this.getEvent(type, true); if (ce2) { ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; } } return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {String} the type, or name of the event * @param prefixed {String} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * * @method after * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ after: function(type, fn) { var a = nativeSlice.call(arguments, 0); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'array': // YArray.each(a[0], function(v) { // v = AFTER_PREFIX + v; // }); // break; case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype); ET.call(Y, { bubbles: false }); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? /** `Y.on()` can do many things: <ul> <li>Subscribe to custom events `publish`ed and `fire`d from Y</li> <li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and `fire`d from any object in the YUI instance sandbox</li> <li>Subscribe to DOM events</li> <li>Subscribe to the execution of a method on any object, effectively treating that method as an event</li> </ul> For custom event subscriptions, pass the custom event name as the first argument and callback as the second. The `this` object in the callback will be `Y` unless an override is passed as the third argument. Y.on('io:complete', function () { Y.MyApp.updateStatus('Transaction complete'); }); To subscribe to DOM events, pass the name of a DOM event as the first argument and a CSS selector string as the third argument after the callback function. Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`, array, or simply omitted (the default is the `window` object). Y.on('click', function (e) { e.preventDefault(); // proceed with ajax form submission var url = this.get('action'); ... }, '#my-form'); The `this` object in DOM event callbacks will be the `Node` targeted by the CSS selector or other identifier. `on()` subscribers for DOM events or custom events `publish`ed with a `defaultFn` can prevent the default behavior with `e.preventDefault()` from the event object passed as the first parameter to the subscription callback. To subscribe to the execution of an object method, pass arguments corresponding to the call signature for <a href="../classes/Do.html#methods_before">`Y.Do.before(...)`</a>. NOTE: The formal parameter list below is for events, not for function injection. See `Y.Do.before` for that signature. @method on @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @see Do.before @for YUI **/ /** Listen for an event one time. Equivalent to `on()`, except that the listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see on @method once @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Listen for an event one time. Equivalent to `once()`, except, like `after()`, the subscription callback executes after all `on()` subscribers and the event's `defaultFn` (if configured) have executed. Like `after()` if any `on()` phase subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()` subscribers will execute. The listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see once @method onceAfter @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Like `on()`, this method creates a subscription to a custom event or to the execution of a method on an object. For events, `after()` subscribers are executed after the event's `defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber. See the <a href="#methods_on">`on()` method</a> for additional subscription options. NOTE: The subscription signature shown is for events, not for function injection. See <a href="../classes/Do.html#methods_after">`Y.Do.after`</a> for that signature. @see on @see Do.after @method after @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [args*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ }, '@VERSION@', {"requires": ["oop"]}); YUI.add('event-custom-complex', function (Y, NAME) { /** * Adds event facades, preventable default behavior, and bubbling. * events. * @module event-custom * @submodule event-custom-complex */ var FACADE, FACADE_KEYS, YObject = Y.Object, key, EMPTY = {}, CEProto = Y.CustomEvent.prototype, ETProto = Y.EventTarget.prototype, mixFacadeProps = function(facade, payload) { var p; for (p in payload) { if (!(FACADE_KEYS.hasOwnProperty(p))) { facade[p] = payload[p]; } } }; /** * Wraps and protects a custom event for use when emitFacade is set to true. * Requires the event-custom-complex module * @class EventFacade * @param e {Event} the custom event * @param currentTarget {HTMLElement} the element the listener was attached to */ Y.EventFacade = function(e, currentTarget) { if (!e) { e = EMPTY; } this._event = e; /** * The arguments passed to fire * @property details * @type Array */ this.details = e.details; /** * The event type, this can be overridden by the fire() payload * @property type * @type string */ this.type = e.type; /** * The real event type * @property _type * @type string * @private */ this._type = e.type; ////////////////////////////////////////////////////// /** * Node reference for the targeted eventtarget * @property target * @type Node */ this.target = e.target; /** * Node reference for the element that the listener was attached to. * @property currentTarget * @type Node */ this.currentTarget = currentTarget; /** * Node reference to the relatedTarget * @property relatedTarget * @type Node */ this.relatedTarget = e.relatedTarget; }; Y.mix(Y.EventFacade.prototype, { /** * Stops the propagation to the next bubble target * @method stopPropagation */ stopPropagation: function() { this._event.stopPropagation(); this.stopped = 1; }, /** * Stops the propagation to the next bubble target and * prevents any additional listeners from being exectued * on the current target. * @method stopImmediatePropagation */ stopImmediatePropagation: function() { this._event.stopImmediatePropagation(); this.stopped = 2; }, /** * Prevents the event's default behavior * @method preventDefault */ preventDefault: function() { this._event.preventDefault(); this.prevented = 1; }, /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ halt: function(immediate) { this._event.halt(immediate); this.prevented = 1; this.stopped = (immediate) ? 2 : 1; } }); CEProto.fireComplex = function(args) { var es, ef, q, queue, ce, ret = true, events, subs, ons, afters, afterQueue, postponed, prevented, preventedFn, defaultFn, self = this, host = self.host || self, next, oldbubble, stack, yuievt = host._yuievt, hasPotentialSubscribers; stack = self.stack; if (stack) { // queue this event if the current item in the queue bubbles if (self.queuable && self.type !== stack.next.type) { self.log('queue ' + self.type); if (!stack.queue) { stack.queue = []; } stack.queue.push([self, args]); return true; } } hasPotentialSubscribers = self.hasSubs() || yuievt.hasTargets || self.broadcast; self.target = self.target || host; self.currentTarget = host; self.details = args.concat(); if (hasPotentialSubscribers) { es = stack || { id: self.id, // id of the first event in the stack next: self, silent: self.silent, stopped: 0, prevented: 0, bubbling: null, type: self.type, // defaultFnQueue: new Y.Queue(), defaultTargetOnly: self.defaultTargetOnly }; subs = self.getSubs(); ons = subs[0]; afters = subs[1]; self.stopped = (self.type !== es.type) ? 0 : es.stopped; self.prevented = (self.type !== es.type) ? 0 : es.prevented; if (self.stoppedFn) { // PERF TODO: Can we replace with callback, like preventedFn. Look into history events = new Y.EventTarget({ fireOnce: true, context: host }); self.events = events; events.on('stopped', self.stoppedFn); } // self.log("Firing " + self + ", " + "args: " + args); self.log("Firing " + self.type); self._facade = null; // kill facade to eliminate stale properties ef = self._getFacade(args); if (ons) { self._procSubs(ons, args, ef); } // bubble if this is hosted in an event target and propagation has not been stopped if (self.bubbles && host.bubble && !self.stopped) { oldbubble = es.bubbling; es.bubbling = self.type; if (es.type !== self.type) { es.stopped = 0; es.prevented = 0; } ret = host.bubble(self, args, null, es); self.stopped = Math.max(self.stopped, es.stopped); self.prevented = Math.max(self.prevented, es.prevented); es.bubbling = oldbubble; } prevented = self.prevented; if (prevented) { preventedFn = self.preventedFn; if (preventedFn) { preventedFn.apply(host, args); } } else { defaultFn = self.defaultFn; if (defaultFn && ((!self.defaultTargetOnly && !es.defaultTargetOnly) || host === ef.target)) { defaultFn.apply(host, args); } } // broadcast listeners are fired as discreet events on the // YUI instance and potentially the YUI global. if (self.broadcast) { self._broadcast(args); } if (afters && !self.prevented && self.stopped < 2) { // Queue the after afterQueue = es.afterQueue; if (es.id === self.id || self.type !== yuievt.bubbling) { self._procSubs(afters, args, ef); if (afterQueue) { while ((next = afterQueue.last())) { next(); } } } else { postponed = afters; if (es.execDefaultCnt) { postponed = Y.merge(postponed); Y.each(postponed, function(s) { s.postponed = true; }); } if (!afterQueue) { es.afterQueue = new Y.Queue(); } es.afterQueue.add(function() { self._procSubs(postponed, args, ef); }); } } self.target = null; if (es.id === self.id) { queue = es.queue; if (queue) { while (queue.length) { q = queue.pop(); ce = q[0]; // set up stack to allow the next item to be processed es.next = ce; ce._fire(q[1]); } } self.stack = null; } ret = !(self.stopped); if (self.type !== yuievt.bubbling) { es.stopped = 0; es.prevented = 0; self.stopped = 0; self.prevented = 0; } // Kill the cached facade to free up memory. // Otherwise we have the facade from the last fire, sitting around forever. self._facade = null; return ret; } else { defaultFn = self.defaultFn; if(defaultFn) { ef = self._getFacade(args); if ((!self.defaultTargetOnly) || (host === ef.target)) { defaultFn.apply(host, args); } } return ret; } }; CEProto._getFacade = function(fireArgs) { var userArgs = this.details, firstArg = userArgs && userArgs[0], firstArgIsObj = (typeof firstArg === "object"), ef = this._facade; if (!ef) { ef = new Y.EventFacade(this, this.currentTarget); } if (firstArgIsObj) { // protect the event facade properties mixFacadeProps(ef, firstArg); // Allow the event type to be faked http://yuilibrary.com/projects/yui3/ticket/2528376 if (firstArg.type) { ef.type = firstArg.type; } if (fireArgs) { fireArgs[0] = ef; } } else { if (fireArgs) { fireArgs.unshift(ef); } } // update the details field with the arguments ef.details = this.details; // use the original target when the event bubbled to this target ef.target = this.originalTarget || this.target; ef.currentTarget = this.currentTarget; ef.stopped = 0; ef.prevented = 0; this._facade = ef; return this._facade; }; /** * Stop propagation to bubble targets * @for CustomEvent * @method stopPropagation */ CEProto.stopPropagation = function() { this.stopped = 1; if (this.stack) { this.stack.stopped = 1; } if (this.events) { this.events.fire('stopped', this); } }; /** * Stops propagation to bubble targets, and prevents any remaining * subscribers on the current target from executing. * @method stopImmediatePropagation */ CEProto.stopImmediatePropagation = function() { this.stopped = 2; if (this.stack) { this.stack.stopped = 2; } if (this.events) { this.events.fire('stopped', this); } }; /** * Prevents the execution of this event's defaultFn * @method preventDefault */ CEProto.preventDefault = function() { if (this.preventable) { this.prevented = 1; if (this.stack) { this.stack.prevented = 1; } } }; /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ CEProto.halt = function(immediate) { if (immediate) { this.stopImmediatePropagation(); } else { this.stopPropagation(); } this.preventDefault(); }; /** * Registers another EventTarget as a bubble target. Bubble order * is determined by the order registered. Multiple targets can * be specified. * * Events can only bubble if emitFacade is true. * * Included in the event-custom-complex submodule. * * @method addTarget * @param o {EventTarget} the target to add * @for EventTarget */ ETProto.addTarget = function(o) { var etState = this._yuievt; if (!etState.targets) { etState.targets = {}; } etState.targets[Y.stamp(o)] = o; etState.hasTargets = true; }; /** * Returns an array of bubble targets for this object. * @method getTargets * @return EventTarget[] */ ETProto.getTargets = function() { var targets = this._yuievt.targets; return targets ? YObject.values(targets) : []; }; /** * Removes a bubble target * @method removeTarget * @param o {EventTarget} the target to remove * @for EventTarget */ ETProto.removeTarget = function(o) { var targets = this._yuievt.targets; if (targets) { delete targets[Y.stamp(o, true)]; if (YObject.size(targets) === 0) { this._yuievt.hasTargets = false; } } }; /** * Propagate an event. Requires the event-custom-complex module. * @method bubble * @param evt {CustomEvent} the custom event to propagate * @return {boolean} the aggregated return value from Event.Custom.fire * @for EventTarget */ ETProto.bubble = function(evt, args, target, es) { var targs = this._yuievt.targets, ret = true, t, ce, i, bc, ce2, type = evt && evt.type, originalTarget = target || (evt && evt.target) || this, oldbubble; if (!evt || ((!evt.stopped) && targs)) { for (i in targs) { if (targs.hasOwnProperty(i)) { t = targs[i]; ce = t._yuievt.events[type]; if (t._hasSiblings) { ce2 = t.getSibling(type, ce); } if (ce2 && !ce) { ce = t.publish(type); } oldbubble = t._yuievt.bubbling; t._yuievt.bubbling = type; // if this event was not published on the bubble target, // continue propagating the event. if (!ce) { if (t._yuievt.hasTargets) { t.bubble(evt, args, originalTarget, es); } } else { if (ce2) { ce.sibling = ce2; } // set the original target to that the target payload on the facade is correct. ce.target = originalTarget; ce.originalTarget = originalTarget; ce.currentTarget = t; bc = ce.broadcast; ce.broadcast = false; // default publish may not have emitFacade true -- that // shouldn't be what the implementer meant to do ce.emitFacade = true; ce.stack = es; // TODO: See what's getting in the way of changing this to use // the more performant ce._fire(args || evt.details || []). // Something in Widget Parent/Child tests is not happy if we // change it - maybe evt.details related? ret = ret && ce.fire.apply(ce, args || evt.details || []); ce.broadcast = bc; ce.originalTarget = null; // stopPropagation() was called if (ce.stopped) { break; } } t._yuievt.bubbling = oldbubble; } } } return ret; }; FACADE = new Y.EventFacade(); FACADE_KEYS = {}; // Flatten whitelist for (key in FACADE) { FACADE_KEYS[key] = true; } }, '@VERSION@', {"requires": ["event-custom-base"]}); YUI.add('node-core', function (Y, NAME) { /** * The Node Utility provides a DOM-like interface for interacting with DOM nodes. * @module node * @main node * @submodule node-core */ /** * The Node class provides a wrapper for manipulating DOM Nodes. * Node properties can be accessed via the set/get methods. * Use `Y.one()` to retrieve Node instances. * * <strong>NOTE:</strong> Node properties are accessed using * the <code>set</code> and <code>get</code> methods. * * @class Node * @constructor * @param {DOMNode} node the DOM node to be mapped to the Node instance. * @uses EventTarget */ // "globals" var DOT = '.', NODE_NAME = 'nodeName', NODE_TYPE = 'nodeType', OWNER_DOCUMENT = 'ownerDocument', TAG_NAME = 'tagName', UID = '_yuid', EMPTY_OBJ = {}, _slice = Array.prototype.slice, Y_DOM = Y.DOM, Y_Node = function(node) { if (!this.getDOMNode) { // support optional "new" return new Y_Node(node); } if (typeof node == 'string') { node = Y_Node._fromString(node); if (!node) { return null; // NOTE: return } } var uid = (node.nodeType !== 9) ? node.uniqueID : node[UID]; if (uid && Y_Node._instances[uid] && Y_Node._instances[uid]._node !== node) { node[UID] = null; // unset existing uid to prevent collision (via clone or hack) } uid = uid || Y.stamp(node); if (!uid) { // stamp failed; likely IE non-HTMLElement uid = Y.guid(); } this[UID] = uid; /** * The underlying DOM node bound to the Y.Node instance * @property _node * @type DOMNode * @private */ this._node = node; this._stateProxy = node; // when augmented with Attribute if (this._initPlugins) { // when augmented with Plugin.Host this._initPlugins(); } }, // used with previous/next/ancestor tests _wrapFn = function(fn) { var ret = null; if (fn) { ret = (typeof fn == 'string') ? function(n) { return Y.Selector.test(n, fn); } : function(n) { return fn(Y.one(n)); }; } return ret; }; // end "globals" Y_Node.ATTRS = {}; Y_Node.DOM_EVENTS = {}; Y_Node._fromString = function(node) { if (node) { if (node.indexOf('doc') === 0) { // doc OR document node = Y.config.doc; } else if (node.indexOf('win') === 0) { // win OR window node = Y.config.win; } else { node = Y.Selector.query(node, null, true); } } return node || null; }; /** * The name of the component * @static * @type String * @property NAME */ Y_Node.NAME = 'node'; /* * The pattern used to identify ARIA attributes */ Y_Node.re_aria = /^(?:role$|aria-)/; Y_Node.SHOW_TRANSITION = 'fadeIn'; Y_Node.HIDE_TRANSITION = 'fadeOut'; /** * A list of Node instances that have been created * @private * @type Object * @property _instances * @static * */ Y_Node._instances = {}; /** * Retrieves the DOM node bound to a Node instance * @method getDOMNode * @static * * @param {Node | HTMLNode} node The Node instance or an HTMLNode * @return {HTMLNode} The DOM node bound to the Node instance. If a DOM node is passed * as the node argument, it is simply returned. */ Y_Node.getDOMNode = function(node) { if (node) { return (node.nodeType) ? node : node._node || null; } return null; }; /** * Checks Node return values and wraps DOM Nodes as Y.Node instances * and DOM Collections / Arrays as Y.NodeList instances. * Other return values just pass thru. If undefined is returned (e.g. no return) * then the Node instance is returned for chainability. * @method scrubVal * @static * * @param {any} node The Node instance or an HTMLNode * @return {Node | NodeList | Any} Depends on what is returned from the DOM node. */ Y_Node.scrubVal = function(val, node) { if (val) { // only truthy values are risky if (typeof val == 'object' || typeof val == 'function') { // safari nodeList === function if (NODE_TYPE in val || Y_DOM.isWindow(val)) {// node || window val = Y.one(val); } else if ((val.item && !val._nodes) || // dom collection or Node instance (val[0] && val[0][NODE_TYPE])) { // array of DOM Nodes val = Y.all(val); } } } else if (typeof val === 'undefined') { val = node; // for chaining } else if (val === null) { val = null; // IE: DOM null not the same as null } return val; }; /** * Adds methods to the Y.Node prototype, routing through scrubVal. * @method addMethod * @static * * @param {String} name The name of the method to add * @param {Function} fn The function that becomes the method * @param {Object} context An optional context to call the method with * (defaults to the Node instance) * @return {any} Depends on what is returned from the DOM node. */ Y_Node.addMethod = function(name, fn, context) { if (name && fn && typeof fn == 'function') { Y_Node.prototype[name] = function() { var args = _slice.call(arguments), node = this, ret; if (args[0] && args[0]._node) { args[0] = args[0]._node; } if (args[1] && args[1]._node) { args[1] = args[1]._node; } args.unshift(node._node); ret = fn.apply(node, args); if (ret) { // scrub truthy ret = Y_Node.scrubVal(ret, node); } (typeof ret != 'undefined') || (ret = node); return ret; }; } else { } }; /** * Imports utility methods to be added as Y.Node methods. * @method importMethod * @static * * @param {Object} host The object that contains the method to import. * @param {String} name The name of the method to import * @param {String} altName An optional name to use in place of the host name * @param {Object} context An optional context to call the method with */ Y_Node.importMethod = function(host, name, altName) { if (typeof name == 'string') { altName = altName || name; Y_Node.addMethod(altName, host[name], host); } else { Y.Array.each(name, function(n) { Y_Node.importMethod(host, n); }); } }; /** * Retrieves a NodeList based on the given CSS selector. * @method all * * @param {string} selector The CSS selector to test against. * @return {NodeList} A NodeList instance for the matching HTMLCollection/Array. * @for YUI */ /** * Returns a single Node instance bound to the node or the * first element matching the given selector. Returns null if no match found. * <strong>Note:</strong> For chaining purposes you may want to * use <code>Y.all</code>, which returns a NodeList when no match is found. * @method one * @param {String | HTMLElement} node a node or Selector * @return {Node | null} a Node instance or null if no match found. * @for YUI */ /** * Returns a single Node instance bound to the node or the * first element matching the given selector. Returns null if no match found. * <strong>Note:</strong> For chaining purposes you may want to * use <code>Y.all</code>, which returns a NodeList when no match is found. * @method one * @static * @param {String | HTMLElement} node a node or Selector * @return {Node | null} a Node instance or null if no match found. * @for Node */ Y_Node.one = function(node) { var instance = null, cachedNode, uid; if (node) { if (typeof node == 'string') { node = Y_Node._fromString(node); if (!node) { return null; // NOTE: return } } else if (node.getDOMNode) { return node; // NOTE: return } if (node.nodeType || Y.DOM.isWindow(node)) { // avoid bad input (numbers, boolean, etc) uid = (node.uniqueID && node.nodeType !== 9) ? node.uniqueID : node._yuid; instance = Y_Node._instances[uid]; // reuse exising instances cachedNode = instance ? instance._node : null; if (!instance || (cachedNode && node !== cachedNode)) { // new Node when nodes don't match instance = new Y_Node(node); if (node.nodeType != 11) { // dont cache document fragment Y_Node._instances[instance[UID]] = instance; // cache node } } } } return instance; }; /** * The default setter for DOM properties * Called with instance context (this === the Node instance) * @method DEFAULT_SETTER * @static * @param {String} name The attribute/property being set * @param {any} val The value to be set * @return {any} The value */ Y_Node.DEFAULT_SETTER = function(name, val) { var node = this._stateProxy, strPath; if (name.indexOf(DOT) > -1) { strPath = name; name = name.split(DOT); // only allow when defined on node Y.Object.setValue(node, name, val); } else if (typeof node[name] != 'undefined') { // pass thru DOM properties node[name] = val; } return val; }; /** * The default getter for DOM properties * Called with instance context (this === the Node instance) * @method DEFAULT_GETTER * @static * @param {String} name The attribute/property to look up * @return {any} The current value */ Y_Node.DEFAULT_GETTER = function(name) { var node = this._stateProxy, val; if (name.indexOf && name.indexOf(DOT) > -1) { val = Y.Object.getValue(node, name.split(DOT)); } else if (typeof node[name] != 'undefined') { // pass thru from DOM val = node[name]; } return val; }; Y.mix(Y_Node.prototype, { DATA_PREFIX: 'data-', /** * The method called when outputting Node instances as strings * @method toString * @return {String} A string representation of the Node instance */ toString: function() { var str = this[UID] + ': not bound to a node', node = this._node, attrs, id, className; if (node) { attrs = node.attributes; id = (attrs && attrs.id) ? node.getAttribute('id') : null; className = (attrs && attrs.className) ? node.getAttribute('className') : null; str = node[NODE_NAME]; if (id) { str += '#' + id; } if (className) { str += '.' + className.replace(' ', '.'); } // TODO: add yuid? str += ' ' + this[UID]; } return str; }, /** * Returns an attribute value on the Node instance. * Unless pre-configured (via `Node.ATTRS`), get hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be queried. * @method get * @param {String} attr The attribute * @return {any} The current value of the attribute */ get: function(attr) { var val; if (this._getAttr) { // use Attribute imple val = this._getAttr(attr); } else { val = this._get(attr); } if (val) { val = Y_Node.scrubVal(val, this); } else if (val === null) { val = null; // IE: DOM null is not true null (even though they ===) } return val; }, /** * Helper method for get. * @method _get * @private * @param {String} attr The attribute * @return {any} The current value of the attribute */ _get: function(attr) { var attrConfig = Y_Node.ATTRS[attr], val; if (attrConfig && attrConfig.getter) { val = attrConfig.getter.call(this); } else if (Y_Node.re_aria.test(attr)) { val = this._node.getAttribute(attr, 2); } else { val = Y_Node.DEFAULT_GETTER.apply(this, arguments); } return val; }, /** * Sets an attribute on the Node instance. * Unless pre-configured (via Node.ATTRS), set hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be set. * To set custom attributes use setAttribute. * @method set * @param {String} attr The attribute to be set. * @param {any} val The value to set the attribute to. * @chainable */ set: function(attr, val) { var attrConfig = Y_Node.ATTRS[attr]; if (this._setAttr) { // use Attribute imple this._setAttr.apply(this, arguments); } else { // use setters inline if (attrConfig && attrConfig.setter) { attrConfig.setter.call(this, val, attr); } else if (Y_Node.re_aria.test(attr)) { // special case Aria this._node.setAttribute(attr, val); } else { Y_Node.DEFAULT_SETTER.apply(this, arguments); } } return this; }, /** * Sets multiple attributes. * @method setAttrs * @param {Object} attrMap an object of name/value pairs to set * @chainable */ setAttrs: function(attrMap) { if (this._setAttrs) { // use Attribute imple this._setAttrs(attrMap); } else { // use setters inline Y.Object.each(attrMap, function(v, n) { this.set(n, v); }, this); } return this; }, /** * Returns an object containing the values for the requested attributes. * @method getAttrs * @param {Array} attrs an array of attributes to get values * @return {Object} An object with attribute name/value pairs. */ getAttrs: function(attrs) { var ret = {}; if (this._getAttrs) { // use Attribute imple this._getAttrs(attrs); } else { // use setters inline Y.Array.each(attrs, function(v, n) { ret[v] = this.get(v); }, this); } return ret; }, /** * Compares nodes to determine if they match. * Node instances can be compared to each other and/or HTMLElements. * @method compareTo * @param {HTMLElement | Node} refNode The reference node to compare to the node. * @return {Boolean} True if the nodes match, false if they do not. */ compareTo: function(refNode) { var node = this._node; if (refNode && refNode._node) { refNode = refNode._node; } return node === refNode; }, /** * Determines whether the node is appended to the document. * @method inDoc * @param {Node|HTMLElement} doc optional An optional document to check against. * Defaults to current document. * @return {Boolean} Whether or not this node is appended to the document. */ inDoc: function(doc) { var node = this._node; doc = (doc) ? doc._node || doc : node[OWNER_DOCUMENT]; if (doc.documentElement) { return Y_DOM.contains(doc.documentElement, node); } }, getById: function(id) { var node = this._node, ret = Y_DOM.byId(id, node[OWNER_DOCUMENT]); if (ret && Y_DOM.contains(node, ret)) { ret = Y.one(ret); } else { ret = null; } return ret; }, /** * Returns the nearest ancestor that passes the test applied by supplied boolean method. * @method ancestor * @param {String | Function} fn A selector string or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * If fn is not passed as an argument, the parent node will be returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @param {String | Function} stopFn optional A selector string or boolean * method to indicate when the search should stop. The search bails when the function * returns true or the selector matches. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} The matching Node instance or null if not found */ ancestor: function(fn, testSelf, stopFn) { // testSelf is optional, check for stopFn as 2nd arg if (arguments.length === 2 && (typeof testSelf == 'string' || typeof testSelf == 'function')) { stopFn = testSelf; } return Y.one(Y_DOM.ancestor(this._node, _wrapFn(fn), testSelf, _wrapFn(stopFn))); }, /** * Returns the ancestors that pass the test applied by supplied boolean method. * @method ancestors * @param {String | Function} fn A selector string or boolean method for testing elements. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * If a function is used, it receives the current node being tested as the only argument. * @return {NodeList} A NodeList instance containing the matching elements */ ancestors: function(fn, testSelf, stopFn) { if (arguments.length === 2 && (typeof testSelf == 'string' || typeof testSelf == 'function')) { stopFn = testSelf; } return Y.all(Y_DOM.ancestors(this._node, _wrapFn(fn), testSelf, _wrapFn(stopFn))); }, /** * Returns the previous matching sibling. * Returns the nearest element node sibling if no method provided. * @method previous * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} Node instance or null if not found */ previous: function(fn, all) { return Y.one(Y_DOM.elementByAxis(this._node, 'previousSibling', _wrapFn(fn), all)); }, /** * Returns the next matching sibling. * Returns the nearest element node sibling if no method provided. * @method next * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} Node instance or null if not found */ next: function(fn, all) { return Y.one(Y_DOM.elementByAxis(this._node, 'nextSibling', _wrapFn(fn), all)); }, /** * Returns all matching siblings. * Returns all siblings if no method provided. * @method siblings * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {NodeList} NodeList instance bound to found siblings */ siblings: function(fn) { return Y.all(Y_DOM.siblings(this._node, _wrapFn(fn))); }, /** * Retrieves a single Node instance, the first element matching the given * CSS selector. * Returns null if no match found. * @method one * * @param {string} selector The CSS selector to test against. * @return {Node | null} A Node instance for the matching HTMLElement or null * if no match found. */ one: function(selector) { return Y.one(Y.Selector.query(selector, this._node, true)); }, /** * Retrieves a NodeList based on the given CSS selector. * @method all * * @param {string} selector The CSS selector to test against. * @return {NodeList} A NodeList instance for the matching HTMLCollection/Array. */ all: function(selector) { var nodelist; if (this._node) { nodelist = Y.all(Y.Selector.query(selector, this._node)); nodelist._query = selector; nodelist._queryRoot = this._node; } return nodelist || Y.all([]); }, // TODO: allow fn test /** * Test if the supplied node matches the supplied selector. * @method test * * @param {string} selector The CSS selector to test against. * @return {boolean} Whether or not the node matches the selector. */ test: function(selector) { return Y.Selector.test(this._node, selector); }, /** * Removes the node from its parent. * Shortcut for myNode.get('parentNode').removeChild(myNode); * @method remove * @param {Boolean} destroy whether or not to call destroy() on the node * after removal. * @chainable * */ remove: function(destroy) { var node = this._node; if (node && node.parentNode) { node.parentNode.removeChild(node); } if (destroy) { this.destroy(); } return this; }, /** * Replace the node with the other node. This is a DOM update only * and does not change the node bound to the Node instance. * Shortcut for myNode.get('parentNode').replaceChild(newNode, myNode); * @method replace * @param {Node | HTMLNode} newNode Node to be inserted * @chainable * */ replace: function(newNode) { var node = this._node; if (typeof newNode == 'string') { newNode = Y_Node.create(newNode); } node.parentNode.replaceChild(Y_Node.getDOMNode(newNode), node); return this; }, /** * @method replaceChild * @for Node * @param {String | HTMLElement | Node} node Node to be inserted * @param {HTMLElement | Node} refNode Node to be replaced * @return {Node} The replaced node */ replaceChild: function(node, refNode) { if (typeof node == 'string') { node = Y_DOM.create(node); } return Y.one(this._node.replaceChild(Y_Node.getDOMNode(node), Y_Node.getDOMNode(refNode))); }, /** * Nulls internal node references, removes any plugins and event listeners. * Note that destroy() will not remove the node from its parent or from the DOM. For that * functionality, call remove(true). * @method destroy * @param {Boolean} recursivePurge (optional) Whether or not to remove listeners from the * node's subtree (default is false) * */ destroy: function(recursive) { var UID = Y.config.doc.uniqueID ? 'uniqueID' : '_yuid', instance; this.purge(); // TODO: only remove events add via this Node if (this.unplug) { // may not be a PluginHost this.unplug(); } this.clearData(); if (recursive) { Y.NodeList.each(this.all('*'), function(node) { instance = Y_Node._instances[node[UID]]; if (instance) { instance.destroy(); } else { // purge in case added by other means Y.Event.purgeElement(node); } }); } this._node = null; this._stateProxy = null; delete Y_Node._instances[this._yuid]; }, /** * Invokes a method on the Node instance * @method invoke * @param {String} method The name of the method to invoke * @param {Any} a, b, c, etc. Arguments to invoke the method with. * @return Whatever the underly method returns. * DOM Nodes and Collections return values * are converted to Node/NodeList instances. * */ invoke: function(method, a, b, c, d, e) { var node = this._node, ret; if (a && a._node) { a = a._node; } if (b && b._node) { b = b._node; } ret = node[method](a, b, c, d, e); return Y_Node.scrubVal(ret, this); }, /** * @method swap * @description Swap DOM locations with the given node. * This does not change which DOM node each Node instance refers to. * @param {Node} otherNode The node to swap with * @chainable */ swap: Y.config.doc.documentElement.swapNode ? function(otherNode) { this._node.swapNode(Y_Node.getDOMNode(otherNode)); } : function(otherNode) { otherNode = Y_Node.getDOMNode(otherNode); var node = this._node, parent = otherNode.parentNode, nextSibling = otherNode.nextSibling; if (nextSibling === node) { parent.insertBefore(node, otherNode); } else if (otherNode === node.nextSibling) { parent.insertBefore(otherNode, node); } else { node.parentNode.replaceChild(otherNode, node); Y_DOM.addHTML(parent, node, nextSibling); } return this; }, hasMethod: function(method) { var node = this._node; return !!(node && method in node && typeof node[method] != 'unknown' && (typeof node[method] == 'function' || String(node[method]).indexOf('function') === 1)); // IE reports as object, prepends space }, isFragment: function() { return (this.get('nodeType') === 11); }, /** * Removes and destroys all of the nodes within the node. * @method empty * @chainable */ empty: function() { this.get('childNodes').remove().destroy(true); return this; }, /** * Returns the DOM node bound to the Node instance * @method getDOMNode * @return {DOMNode} */ getDOMNode: function() { return this._node; } }, true); Y.Node = Y_Node; Y.one = Y_Node.one; /** * The NodeList module provides support for managing collections of Nodes. * @module node * @submodule node-core */ /** * The NodeList class provides a wrapper for manipulating DOM NodeLists. * NodeList properties can be accessed via the set/get methods. * Use Y.all() to retrieve NodeList instances. * * @class NodeList * @constructor * @param nodes {String|element|Node|Array} A selector, DOM element, Node, list of DOM elements, or list of Nodes with which to populate this NodeList. */ var NodeList = function(nodes) { var tmp = []; if (nodes) { if (typeof nodes === 'string') { // selector query this._query = nodes; nodes = Y.Selector.query(nodes); } else if (nodes.nodeType || Y_DOM.isWindow(nodes)) { // domNode || window nodes = [nodes]; } else if (nodes._node) { // Y.Node nodes = [nodes._node]; } else if (nodes[0] && nodes[0]._node) { // allow array of Y.Nodes Y.Array.each(nodes, function(node) { if (node._node) { tmp.push(node._node); } }); nodes = tmp; } else { // array of domNodes or domNodeList (no mixed array of Y.Node/domNodes) nodes = Y.Array(nodes, 0, true); } } /** * The underlying array of DOM nodes bound to the Y.NodeList instance * @property _nodes * @private */ this._nodes = nodes || []; }; NodeList.NAME = 'NodeList'; /** * Retrieves the DOM nodes bound to a NodeList instance * @method getDOMNodes * @static * * @param {NodeList} nodelist The NodeList instance * @return {Array} The array of DOM nodes bound to the NodeList */ NodeList.getDOMNodes = function(nodelist) { return (nodelist && nodelist._nodes) ? nodelist._nodes : nodelist; }; NodeList.each = function(instance, fn, context) { var nodes = instance._nodes; if (nodes && nodes.length) { Y.Array.each(nodes, fn, context || instance); } else { } }; NodeList.addMethod = function(name, fn, context) { if (name && fn) { NodeList.prototype[name] = function() { var ret = [], args = arguments; Y.Array.each(this._nodes, function(node) { var UID = (node.uniqueID && node.nodeType !== 9 ) ? 'uniqueID' : '_yuid', instance = Y.Node._instances[node[UID]], ctx, result; if (!instance) { instance = NodeList._getTempNode(node); } ctx = context || instance; result = fn.apply(ctx, args); if (result !== undefined && result !== instance) { ret[ret.length] = result; } }); // TODO: remove tmp pointer return ret.length ? ret : this; }; } else { } }; NodeList.importMethod = function(host, name, altName) { if (typeof name === 'string') { altName = altName || name; NodeList.addMethod(name, host[name]); } else { Y.Array.each(name, function(n) { NodeList.importMethod(host, n); }); } }; NodeList._getTempNode = function(node) { var tmp = NodeList._tempNode; if (!tmp) { tmp = Y.Node.create('<div></div>'); NodeList._tempNode = tmp; } tmp._node = node; tmp._stateProxy = node; return tmp; }; Y.mix(NodeList.prototype, { _invoke: function(method, args, getter) { var ret = (getter) ? [] : this; this.each(function(node) { var val = node[method].apply(node, args); if (getter) { ret.push(val); } }); return ret; }, /** * Retrieves the Node instance at the given index. * @method item * * @param {Number} index The index of the target Node. * @return {Node} The Node instance at the given index. */ item: function(index) { return Y.one((this._nodes || [])[index]); }, /** * Applies the given function to each Node in the NodeList. * @method each * @param {Function} fn The function to apply. It receives 3 arguments: * the current node instance, the node's index, and the NodeList instance * @param {Object} context optional An optional context to apply the function with * Default context is the current Node instance * @chainable */ each: function(fn, context) { var instance = this; Y.Array.each(this._nodes, function(node, index) { node = Y.one(node); return fn.call(context || node, node, index, instance); }); return instance; }, batch: function(fn, context) { var nodelist = this; Y.Array.each(this._nodes, function(node, index) { var instance = Y.Node._instances[node[UID]]; if (!instance) { instance = NodeList._getTempNode(node); } return fn.call(context || instance, instance, index, nodelist); }); return nodelist; }, /** * Executes the function once for each node until a true value is returned. * @method some * @param {Function} fn The function to apply. It receives 3 arguments: * the current node instance, the node's index, and the NodeList instance * @param {Object} context optional An optional context to execute the function from. * Default context is the current Node instance * @return {Boolean} Whether or not the function returned true for any node. */ some: function(fn, context) { var instance = this; return Y.Array.some(this._nodes, function(node, index) { node = Y.one(node); context = context || node; return fn.call(context, node, index, instance); }); }, /** * Creates a documenFragment from the nodes bound to the NodeList instance * @method toFrag * @return {Node} a Node instance bound to the documentFragment */ toFrag: function() { return Y.one(Y.DOM._nl2frag(this._nodes)); }, /** * Returns the index of the node in the NodeList instance * or -1 if the node isn't found. * @method indexOf * @param {Node | DOMNode} node the node to search for * @return {Int} the index of the node value or -1 if not found */ indexOf: function(node) { return Y.Array.indexOf(this._nodes, Y.Node.getDOMNode(node)); }, /** * Filters the NodeList instance down to only nodes matching the given selector. * @method filter * @param {String} selector The selector to filter against * @return {NodeList} NodeList containing the updated collection * @see Selector */ filter: function(selector) { return Y.all(Y.Selector.filter(this._nodes, selector)); }, /** * Creates a new NodeList containing all nodes at every n indices, where * remainder n % index equals r. * (zero-based index). * @method modulus * @param {Int} n The offset to use (return every nth node) * @param {Int} r An optional remainder to use with the modulus operation (defaults to zero) * @return {NodeList} NodeList containing the updated collection */ modulus: function(n, r) { r = r || 0; var nodes = []; NodeList.each(this, function(node, i) { if (i % n === r) { nodes.push(node); } }); return Y.all(nodes); }, /** * Creates a new NodeList containing all nodes at odd indices * (zero-based index). * @method odd * @return {NodeList} NodeList containing the updated collection */ odd: function() { return this.modulus(2, 1); }, /** * Creates a new NodeList containing all nodes at even indices * (zero-based index), including zero. * @method even * @return {NodeList} NodeList containing the updated collection */ even: function() { return this.modulus(2); }, destructor: function() { }, /** * Reruns the initial query, when created using a selector query * @method refresh * @chainable */ refresh: function() { var doc, nodes = this._nodes, query = this._query, root = this._queryRoot; if (query) { if (!root) { if (nodes && nodes[0] && nodes[0].ownerDocument) { root = nodes[0].ownerDocument; } } this._nodes = Y.Selector.query(query, root); } return this; }, /** * Returns the current number of items in the NodeList. * @method size * @return {Int} The number of items in the NodeList. */ size: function() { return this._nodes.length; }, /** * Determines if the instance is bound to any nodes * @method isEmpty * @return {Boolean} Whether or not the NodeList is bound to any nodes */ isEmpty: function() { return this._nodes.length < 1; }, toString: function() { var str = '', errorMsg = this[UID] + ': not bound to any nodes', nodes = this._nodes, node; if (nodes && nodes[0]) { node = nodes[0]; str += node[NODE_NAME]; if (node.id) { str += '#' + node.id; } if (node.className) { str += '.' + node.className.replace(' ', '.'); } if (nodes.length > 1) { str += '...[' + nodes.length + ' items]'; } } return str || errorMsg; }, /** * Returns the DOM node bound to the Node instance * @method getDOMNodes * @return {Array} */ getDOMNodes: function() { return this._nodes; } }, true); NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance. Nulls internal node references, * removes any plugins and event listeners * @method destroy * @param {Boolean} recursivePurge (optional) Whether or not to * remove listeners from the node's subtree (default is false) * @see Node.destroy */ 'destroy', /** * Called on each Node instance. Removes and destroys all of the nodes * within the node * @method empty * @chainable * @see Node.empty */ 'empty', /** * Called on each Node instance. Removes the node from its parent. * Shortcut for myNode.get('parentNode').removeChild(myNode); * @method remove * @param {Boolean} destroy whether or not to call destroy() on the node * after removal. * @chainable * @see Node.remove */ 'remove', /** * Called on each Node instance. Sets an attribute on the Node instance. * Unless pre-configured (via Node.ATTRS), set hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be set. * To set custom attributes use setAttribute. * @method set * @param {String} attr The attribute to be set. * @param {any} val The value to set the attribute to. * @chainable * @see Node.set */ 'set' ]); // one-off implementation to convert array of Nodes to NodeList // e.g. Y.all('input').get('parentNode'); /** Called on each Node instance * @method get * @see Node */ NodeList.prototype.get = function(attr) { var ret = [], nodes = this._nodes, isNodeList = false, getTemp = NodeList._getTempNode, instance, val; if (nodes[0]) { instance = Y.Node._instances[nodes[0]._yuid] || getTemp(nodes[0]); val = instance._get(attr); if (val && val.nodeType) { isNodeList = true; } } Y.Array.each(nodes, function(node) { instance = Y.Node._instances[node._yuid]; if (!instance) { instance = getTemp(node); } val = instance._get(attr); if (!isNodeList) { // convert array of Nodes to NodeList val = Y.Node.scrubVal(val, instance); } ret.push(val); }); return (isNodeList) ? Y.all(ret) : ret; }; Y.NodeList = NodeList; Y.all = function(nodes) { return new NodeList(nodes); }; Y.Node.all = Y.all; /** * @module node * @submodule node-core */ var Y_NodeList = Y.NodeList, ArrayProto = Array.prototype, ArrayMethods = { /** Returns a new NodeList combining the given NodeList(s) * @for NodeList * @method concat * @param {NodeList | Array} valueN Arrays/NodeLists and/or values to * concatenate to the resulting NodeList * @return {NodeList} A new NodeList comprised of this NodeList joined with the input. */ 'concat': 1, /** Removes the last from the NodeList and returns it. * @for NodeList * @method pop * @return {Node | null} The last item in the NodeList, or null if the list is empty. */ 'pop': 0, /** Adds the given Node(s) to the end of the NodeList. * @for NodeList * @method push * @param {Node | DOMNode} nodes One or more nodes to add to the end of the NodeList. */ 'push': 0, /** Removes the first item from the NodeList and returns it. * @for NodeList * @method shift * @return {Node | null} The first item in the NodeList, or null if the NodeList is empty. */ 'shift': 0, /** Returns a new NodeList comprising the Nodes in the given range. * @for NodeList * @method slice * @param {Number} begin Zero-based index at which to begin extraction. As a negative index, start indicates an offset from the end of the sequence. slice(-2) extracts the second-to-last element and the last element in the sequence. * @param {Number} end Zero-based index at which to end extraction. slice extracts up to but not including end. slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3). As a negative index, end indicates an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence. If end is omitted, slice extracts to the end of the sequence. * @return {NodeList} A new NodeList comprised of this NodeList joined with the input. */ 'slice': 1, /** Changes the content of the NodeList, adding new elements while removing old elements. * @for NodeList * @method splice * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end. * @param {Number} howMany An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed. In this case, you should specify at least one new element. If no howMany parameter is specified (second syntax above, which is a SpiderMonkey extension), all elements after index are removed. * {Node | DOMNode| element1, ..., elementN The elements to add to the array. If you don't specify any elements, splice simply removes elements from the array. * @return {NodeList} The element(s) removed. */ 'splice': 1, /** Adds the given Node(s) to the beginning of the NodeList. * @for NodeList * @method unshift * @param {Node | DOMNode} nodes One or more nodes to add to the NodeList. */ 'unshift': 0 }; Y.Object.each(ArrayMethods, function(returnNodeList, name) { Y_NodeList.prototype[name] = function() { var args = [], i = 0, arg, ret; while (typeof (arg = arguments[i++]) != 'undefined') { // use DOM nodes/nodeLists args.push(arg._node || arg._nodes || arg); } ret = ArrayProto[name].apply(this._nodes, args); if (returnNodeList) { ret = Y.all(ret); } else { ret = Y.Node.scrubVal(ret); } return ret; }; }); /** * @module node * @submodule node-core */ Y.Array.each([ /** * Passes through to DOM method. * @for Node * @method removeChild * @param {HTMLElement | Node} node Node to be removed * @return {Node} The removed node */ 'removeChild', /** * Passes through to DOM method. * @method hasChildNodes * @return {Boolean} Whether or not the node has any childNodes */ 'hasChildNodes', /** * Passes through to DOM method. * @method cloneNode * @param {Boolean} deep Whether or not to perform a deep clone, which includes * subtree and attributes * @return {Node} The clone */ 'cloneNode', /** * Passes through to DOM method. * @method hasAttribute * @param {String} attribute The attribute to test for * @return {Boolean} Whether or not the attribute is present */ 'hasAttribute', /** * Passes through to DOM method. * @method scrollIntoView * @chainable */ 'scrollIntoView', /** * Passes through to DOM method. * @method getElementsByTagName * @param {String} tagName The tagName to collect * @return {NodeList} A NodeList representing the HTMLCollection */ 'getElementsByTagName', /** * Passes through to DOM method. * @method focus * @chainable */ 'focus', /** * Passes through to DOM method. * @method blur * @chainable */ 'blur', /** * Passes through to DOM method. * Only valid on FORM elements * @method submit * @chainable */ 'submit', /** * Passes through to DOM method. * Only valid on FORM elements * @method reset * @chainable */ 'reset', /** * Passes through to DOM method. * @method select * @chainable */ 'select', /** * Passes through to DOM method. * Only valid on TABLE elements * @method createCaption * @chainable */ 'createCaption' ], function(method) { Y.Node.prototype[method] = function(arg1, arg2, arg3) { var ret = this.invoke(method, arg1, arg2, arg3); return ret; }; }); /** * Passes through to DOM method. * @method removeAttribute * @param {String} attribute The attribute to be removed * @chainable */ // one-off implementation due to IE returning boolean, breaking chaining Y.Node.prototype.removeAttribute = function(attr) { var node = this._node; if (node) { node.removeAttribute(attr, 0); // comma zero for IE < 8 to force case-insensitive } return this; }; Y.Node.importMethod(Y.DOM, [ /** * Determines whether the node is an ancestor of another HTML element in the DOM hierarchy. * @method contains * @param {Node | HTMLElement} needle The possible node or descendent * @return {Boolean} Whether or not this node is the needle its ancestor */ 'contains', /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @for Node * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @for Node * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute', /** * Wraps the given HTML around the node. * @method wrap * @param {String} html The markup to wrap around the node. * @chainable * @for Node */ 'wrap', /** * Removes the node's parent node. * @method unwrap * @chainable */ 'unwrap', /** * Applies a unique ID to the node if none exists * @method generateID * @return {String} The existing or generated ID */ 'generateID' ]); Y.NodeList.importMethod(Y.Node.prototype, [ /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @see Node * @for NodeList * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute', /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @see Node * @for NodeList * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows for removing attributes on DOM nodes. * This passes through to the DOM node, allowing for custom attributes. * @method removeAttribute * @see Node * @for NodeList * @param {string} name The attribute to remove */ 'removeAttribute', /** * Removes the parent node from node in the list. * @method unwrap * @chainable */ 'unwrap', /** * Wraps the given HTML around each node. * @method wrap * @param {String} html The markup to wrap around the node. * @chainable */ 'wrap', /** * Applies a unique ID to each node if none exists * @method generateID * @return {String} The existing or generated ID */ 'generateID' ]); }, '@VERSION@', {"requires": ["dom-core", "selector"]}); YUI.add('node-base', function (Y, NAME) { /** * @module node * @submodule node-base */ var methods = [ /** * Determines whether each node has the given className. * @method hasClass * @for Node * @param {String} className the class name to search for * @return {Boolean} Whether or not the element has the specified class */ 'hasClass', /** * Adds a class name to each node. * @method addClass * @param {String} className the class name to add to the node's class attribute * @chainable */ 'addClass', /** * Removes a class name from each node. * @method removeClass * @param {String} className the class name to remove from the node's class attribute * @chainable */ 'removeClass', /** * Replace a class with another class for each node. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @chainable */ 'replaceClass', /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @param {String} className the class name to be toggled * @param {Boolean} force Option to force adding or removing the class. * @chainable */ 'toggleClass' ]; Y.Node.importMethod(Y.DOM, methods); /** * Determines whether each node has the given className. * @method hasClass * @see Node.hasClass * @for NodeList * @param {String} className the class name to search for * @return {Array} An array of booleans for each node bound to the NodeList. */ /** * Adds a class name to each node. * @method addClass * @see Node.addClass * @param {String} className the class name to add to the node's class attribute * @chainable */ /** * Removes a class name from each node. * @method removeClass * @see Node.removeClass * @param {String} className the class name to remove from the node's class attribute * @chainable */ /** * Replace a class with another class for each node. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @see Node.replaceClass * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @chainable */ /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @see Node.toggleClass * @param {String} className the class name to be toggled * @chainable */ Y.NodeList.importMethod(Y.Node.prototype, methods); /** * @module node * @submodule node-base */ var Y_Node = Y.Node, Y_DOM = Y.DOM; /** * Returns a new dom node using the provided markup string. * @method create * @static * @param {String} html The markup used to create the element * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {HTMLDocument} doc An optional document context * @return {Node} A Node instance bound to a DOM node or fragment * @for Node */ Y_Node.create = function(html, doc) { if (doc && doc._node) { doc = doc._node; } return Y.one(Y_DOM.create(html, doc)); }; Y.mix(Y_Node.prototype, { /** * Creates a new Node using the provided markup string. * @method create * @param {String} html The markup used to create the element. * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {HTMLDocument} doc An optional document context * @return {Node} A Node instance bound to a DOM node or fragment */ create: Y_Node.create, /** * Inserts the content before the reference node. * @method insert * @param {String | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {Int | Node | HTMLElement | String} where The position to insert at. * Possible "where" arguments * <dl> * <dt>Y.Node</dt> * <dd>The Node to insert before</dd> * <dt>HTMLElement</dt> * <dd>The element to insert before</dd> * <dt>Int</dt> * <dd>The index of the child element to insert before</dd> * <dt>"replace"</dt> * <dd>Replaces the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts before the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts content before the node</dd> * <dt>"after"</dt> * <dd>Inserts content after the node</dd> * </dl> * @chainable */ insert: function(content, where) { this._insert(content, where); return this; }, _insert: function(content, where) { var node = this._node, ret = null; if (typeof where == 'number') { // allow index where = this._node.childNodes[where]; } else if (where && where._node) { // Node where = where._node; } if (content && typeof content != 'string') { // allow Node or NodeList/Array instances content = content._node || content._nodes || content; } ret = Y_DOM.addHTML(node, content, where); return ret; }, /** * Inserts the content as the firstChild of the node. * @method prepend * @param {String | Node | HTMLElement} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @chainable */ prepend: function(content) { return this.insert(content, 0); }, /** * Inserts the content as the lastChild of the node. * @method append * @param {String | Node | HTMLElement} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @chainable */ append: function(content) { return this.insert(content, null); }, /** * @method appendChild * @param {String | HTMLElement | Node} node Node to be appended * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @return {Node} The appended node */ appendChild: function(node) { return Y_Node.scrubVal(this._insert(node)); }, /** * @method insertBefore * @param {String | HTMLElement | Node} newNode Node to be appended * @param {HTMLElement | Node} refNode Node to be inserted before * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @return {Node} The inserted node */ insertBefore: function(newNode, refNode) { return Y.Node.scrubVal(this._insert(newNode, refNode)); }, /** * Appends the node to the given node. * @method appendTo * @param {Node | HTMLElement} node The node to append to * @chainable */ appendTo: function(node) { Y.one(node).append(this); return this; }, /** * Replaces the node's current content with the content. * Note that this passes to innerHTML and is not escaped. * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content or `set('text')` to add as text. * @method setContent * @deprecated Use setHTML * @param {String | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * @chainable */ setContent: function(content) { this._insert(content, 'replace'); return this; }, /** * Returns the node's current content (e.g. innerHTML) * @method getContent * @deprecated Use getHTML * @return {String} The current content */ getContent: function(content) { return this.get('innerHTML'); } }); /** * Replaces the node's current html content with the content provided. * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @method setHTML * @param {String | HTML | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * @chainable */ Y.Node.prototype.setHTML = Y.Node.prototype.setContent; /** * Returns the node's current html content (e.g. innerHTML) * @method getHTML * @return {String} The html content */ Y.Node.prototype.getHTML = Y.Node.prototype.getContent; Y.NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance * @for NodeList * @method append * @see Node.append */ 'append', /** * Called on each Node instance * @for NodeList * @method insert * @see Node.insert */ 'insert', /** * Called on each Node instance * @for NodeList * @method appendChild * @see Node.appendChild */ 'appendChild', /** * Called on each Node instance * @for NodeList * @method insertBefore * @see Node.insertBefore */ 'insertBefore', /** * Called on each Node instance * @for NodeList * @method prepend * @see Node.prepend */ 'prepend', /** * Called on each Node instance * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @for NodeList * @method setContent * @deprecated Use setHTML */ 'setContent', /** * Called on each Node instance * @for NodeList * @method getContent * @deprecated Use getHTML */ 'getContent', /** * Called on each Node instance * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @for NodeList * @method setHTML * @see Node.setHTML */ 'setHTML', /** * Called on each Node instance * @for NodeList * @method getHTML * @see Node.getHTML */ 'getHTML' ]); /** * @module node * @submodule node-base */ var Y_Node = Y.Node, Y_DOM = Y.DOM; /** * Static collection of configuration attributes for special handling * @property ATTRS * @static * @type object */ Y_Node.ATTRS = { /** * Allows for getting and setting the text of an element. * Formatting is preserved and special characters are treated literally. * @config text * @type String */ text: { getter: function() { return Y_DOM.getText(this._node); }, setter: function(content) { Y_DOM.setText(this._node, content); return content; } }, /** * Allows for getting and setting the text of an element. * Formatting is preserved and special characters are treated literally. * @config for * @type String */ 'for': { getter: function() { return Y_DOM.getAttribute(this._node, 'for'); }, setter: function(val) { Y_DOM.setAttribute(this._node, 'for', val); return val; } }, 'options': { getter: function() { return this._node.getElementsByTagName('option'); } }, /** * Returns a NodeList instance of all HTMLElement children. * @readOnly * @config children * @type NodeList */ 'children': { getter: function() { var node = this._node, children = node.children, childNodes, i, len; if (!children) { childNodes = node.childNodes; children = []; for (i = 0, len = childNodes.length; i < len; ++i) { if (childNodes[i].tagName) { children[children.length] = childNodes[i]; } } } return Y.all(children); } }, value: { getter: function() { return Y_DOM.getValue(this._node); }, setter: function(val) { Y_DOM.setValue(this._node, val); return val; } } }; Y.Node.importMethod(Y.DOM, [ /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @for Node * @for NodeList * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @for Node * @for NodeList * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute' ]); /** * @module node * @submodule node-base */ var Y_Node = Y.Node; var Y_NodeList = Y.NodeList; /** * List of events that route to DOM events * @static * @property DOM_EVENTS * @for Node */ Y_Node.DOM_EVENTS = { abort: 1, beforeunload: 1, blur: 1, change: 1, click: 1, close: 1, command: 1, contextmenu: 1, dblclick: 1, DOMMouseScroll: 1, drag: 1, dragstart: 1, dragenter: 1, dragover: 1, dragleave: 1, dragend: 1, drop: 1, error: 1, focus: 1, key: 1, keydown: 1, keypress: 1, keyup: 1, load: 1, message: 1, mousedown: 1, mouseenter: 1, mouseleave: 1, mousemove: 1, mousemultiwheel: 1, mouseout: 1, mouseover: 1, mouseup: 1, mousewheel: 1, orientationchange: 1, reset: 1, resize: 1, select: 1, selectstart: 1, submit: 1, scroll: 1, textInput: 1, unload: 1 }; // Add custom event adaptors to this list. This will make it so // that delegate, key, available, contentready, etc all will // be available through Node.on Y.mix(Y_Node.DOM_EVENTS, Y.Env.evt.plugins); Y.augment(Y_Node, Y.EventTarget); Y.mix(Y_Node.prototype, { /** * Removes event listeners from the node and (optionally) its subtree * @method purge * @param {Boolean} recurse (optional) Whether or not to remove listeners from the * node's subtree * @param {String} type (optional) Only remove listeners of the specified type * @chainable * */ purge: function(recurse, type) { Y.Event.purgeElement(this._node, recurse, type); return this; } }); Y.mix(Y.NodeList.prototype, { _prepEvtArgs: function(type, fn, context) { // map to Y.on/after signature (type, fn, nodes, context, arg1, arg2, etc) var args = Y.Array(arguments, 0, true); if (args.length < 2) { // type only (event hash) just add nodes args[2] = this._nodes; } else { args.splice(2, 0, this._nodes); } args[3] = context || this; // default to NodeList instance as context return args; }, /** Subscribe a callback function for each `Node` in the collection to execute in response to a DOM event. NOTE: Generally, the `on()` method should be avoided on `NodeLists`, in favor of using event delegation from a parent Node. See the Event user guide for details. Most DOM events are associated with a preventable default behavior, such as link clicks navigating to a new page. Callbacks are passed a `DOMEventFacade` object as their first argument (usually called `e`) that can be used to prevent this default behavior with `e.preventDefault()`. See the `DOMEventFacade` API for all available properties and methods on the object. By default, the `this` object will be the `NodeList` that the subscription came from, <em>not the `Node` that received the event</em>. Use `e.currentTarget` to refer to the `Node`. Returning `false` from a callback is supported as an alternative to calling `e.preventDefault(); e.stopPropagation();`. However, it is recommended to use the event methods. @example Y.all(".sku").on("keydown", function (e) { if (e.keyCode === 13) { e.preventDefault(); // Use e.currentTarget to refer to the individual Node var item = Y.MyApp.searchInventory( e.currentTarget.get('value') ); // etc ... } }); @method on @param {String} type The name of the event @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching that subscription @for NodeList **/ on: function(type, fn, context) { return Y.on.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList. * @method once * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ once: function(type, fn, context) { return Y.once.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an event listener to each Node bound to the NodeList. * The handler is called only after all on() handlers are called * and the event is not prevented. * @method after * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ after: function(type, fn, context) { return Y.after.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList * that will be called only after all on() handlers are called and the * event is not prevented. * * @method onceAfter * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ onceAfter: function(type, fn, context) { return Y.onceAfter.apply(Y, this._prepEvtArgs.apply(this, arguments)); } }); Y_NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance * @method detach * @see Node.detach * @for NodeList */ 'detach', /** Called on each Node instance * @method detachAll * @see Node.detachAll * @for NodeList */ 'detachAll' ]); /** Subscribe a callback function to execute in response to a DOM event or custom event. Most DOM events are associated with a preventable default behavior such as link clicks navigating to a new page. Callbacks are passed a `DOMEventFacade` object as their first argument (usually called `e`) that can be used to prevent this default behavior with `e.preventDefault()`. See the `DOMEventFacade` API for all available properties and methods on the object. If the event name passed as the first parameter is not a whitelisted DOM event, it will be treated as a custom event subscriptions, allowing `node.fire('customEventName')` later in the code. Refer to the Event user guide for the full DOM event whitelist. By default, the `this` object in the callback will refer to the subscribed `Node`. Returning `false` from a callback is supported as an alternative to calling `e.preventDefault(); e.stopPropagation();`. However, it is recommended to use the event methods. @example Y.one("#my-form").on("submit", function (e) { e.preventDefault(); // proceed with ajax form submission instead... }); @method on @param {String} type The name of the event @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching that subscription @for Node **/ Y.mix(Y.Node.ATTRS, { offsetHeight: { setter: function(h) { Y.DOM.setHeight(this._node, h); return h; }, getter: function() { return this._node.offsetHeight; } }, offsetWidth: { setter: function(w) { Y.DOM.setWidth(this._node, w); return w; }, getter: function() { return this._node.offsetWidth; } } }); Y.mix(Y.Node.prototype, { sizeTo: function(w, h) { var node; if (arguments.length < 2) { node = Y.one(w); w = node.get('offsetWidth'); h = node.get('offsetHeight'); } this.setAttrs({ offsetWidth: w, offsetHeight: h }); } }); /** * @module node * @submodule node-base */ var Y_Node = Y.Node; Y.mix(Y_Node.prototype, { /** * Makes the node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @for Node * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ show: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(true, callback); return this; }, /** * The implementation for showing nodes. * Default is to toggle the style.display property. * @method _show * @protected * @chainable */ _show: function() { this.setStyle('display', ''); }, _isHidden: function() { return Y.DOM.getStyle(this._node, 'display') === 'none'; }, /** * Displays or hides the node. * If the "transition" module is loaded, toggleView optionally * animates the toggling of the node using given named effect. * @method toggleView * @for Node * @param {String} [name] An optional string value to use as transition effect. * @param {Boolean} [on] An optional boolean value to force the node to be shown or hidden * @param {Function} [callback] An optional function to run after the transition completes. * @chainable */ toggleView: function(on, callback) { this._toggleView.apply(this, arguments); return this; }, _toggleView: function(on, callback) { callback = arguments[arguments.length - 1]; // base on current state if not forcing if (typeof on != 'boolean') { on = (this._isHidden()) ? 1 : 0; } if (on) { this._show(); } else { this._hide(); } if (typeof callback == 'function') { callback.call(this); } return this; }, /** * Hides the node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ hide: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(false, callback); return this; }, /** * The implementation for hiding nodes. * Default is to toggle the style.display property. * @method _hide * @protected * @chainable */ _hide: function() { this.setStyle('display', 'none'); } }); Y.NodeList.importMethod(Y.Node.prototype, [ /** * Makes each node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @for NodeList * @chainable */ 'show', /** * Hides each node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ 'hide', /** * Displays or hides each node. * If the "transition" module is loaded, toggleView optionally * animates the toggling of the nodes using given named effect. * @method toggleView * @param {String} [name] An optional string value to use as transition effect. * @param {Boolean} [on] An optional boolean value to force the nodes to be shown or hidden * @param {Function} [callback] An optional function to run after the transition completes. * @chainable */ 'toggleView' ]); if (!Y.config.doc.documentElement.hasAttribute) { // IE < 8 Y.Node.prototype.hasAttribute = function(attr) { if (attr === 'value') { if (this.get('value') !== "") { // IE < 8 fails to populate specified when set in HTML return true; } } return !!(this._node.attributes[attr] && this._node.attributes[attr].specified); }; } // IE throws an error when calling focus() on an element that's invisible, not // displayed, or disabled. Y.Node.prototype.focus = function () { try { this._node.focus(); } catch (e) { } return this; }; // IE throws error when setting input.type = 'hidden', // input.setAttribute('type', 'hidden') and input.attributes.type.value = 'hidden' Y.Node.ATTRS.type = { setter: function(val) { if (val === 'hidden') { try { this._node.type = 'hidden'; } catch(e) { this.setStyle('display', 'none'); this._inputType = 'hidden'; } } else { try { // IE errors when changing the type from "hidden' this._node.type = val; } catch (e) { } } return val; }, getter: function() { return this._inputType || this._node.type; }, _bypassProxy: true // don't update DOM when using with Attribute }; if (Y.config.doc.createElement('form').elements.nodeType) { // IE: elements collection is also FORM node which trips up scrubVal. Y.Node.ATTRS.elements = { getter: function() { return this.all('input, textarea, button, select'); } }; } /** * Provides methods for managing custom Node data. * * @module node * @main node * @submodule node-data */ Y.mix(Y.Node.prototype, { _initData: function() { if (! ('_data' in this)) { this._data = {}; } }, /** * @method getData * @for Node * @description Retrieves arbitrary data stored on a Node instance. * If no data is associated with the Node, it will attempt to retrieve * a value from the corresponding HTML data attribute. (e.g. node.getData('foo') * will check node.getAttribute('data-foo')). * @param {string} name Optional name of the data field to retrieve. * If no name is given, all data is returned. * @return {any | Object} Whatever is stored at the given field, * or an object hash of all fields. */ getData: function(name) { this._initData(); var data = this._data, ret = data; if (arguments.length) { // single field if (name in data) { ret = data[name]; } else { // initialize from HTML attribute ret = this._getDataAttribute(name); } } else if (typeof data == 'object' && data !== null) { // all fields ret = {}; Y.Object.each(data, function(v, n) { ret[n] = v; }); ret = this._getDataAttributes(ret); } return ret; }, _getDataAttributes: function(ret) { ret = ret || {}; var i = 0, attrs = this._node.attributes, len = attrs.length, prefix = this.DATA_PREFIX, prefixLength = prefix.length, name; while (i < len) { name = attrs[i].name; if (name.indexOf(prefix) === 0) { name = name.substr(prefixLength); if (!(name in ret)) { // only merge if not already stored ret[name] = this._getDataAttribute(name); } } i += 1; } return ret; }, _getDataAttribute: function(name) { name = this.DATA_PREFIX + name; var node = this._node, attrs = node.attributes, data = attrs && attrs[name] && attrs[name].value; return data; }, /** * @method setData * @for Node * @description Stores arbitrary data on a Node instance. * This is not stored with the DOM node. * @param {string} name The name of the field to set. If no val * is given, name is treated as the data and overrides any existing data. * @param {any} val The value to be assigned to the field. * @chainable */ setData: function(name, val) { this._initData(); if (arguments.length > 1) { this._data[name] = val; } else { this._data = name; } return this; }, /** * @method clearData * @for Node * @description Clears internally stored data. * @param {string} name The name of the field to clear. If no name * is given, all data is cleared. * @chainable */ clearData: function(name) { if ('_data' in this) { if (typeof name != 'undefined') { delete this._data[name]; } else { delete this._data; } } return this; } }); Y.mix(Y.NodeList.prototype, { /** * @method getData * @for NodeList * @description Retrieves arbitrary data stored on each Node instance * bound to the NodeList. * @see Node * @param {string} name Optional name of the data field to retrieve. * If no name is given, all data is returned. * @return {Array} An array containing all of the data for each Node instance. * or an object hash of all fields. */ getData: function(name) { var args = (arguments.length) ? [name] : []; return this._invoke('getData', args, true); }, /** * @method setData * @for NodeList * @description Stores arbitrary data on each Node instance bound to the * NodeList. This is not stored with the DOM node. * @param {string} name The name of the field to set. If no name * is given, name is treated as the data and overrides any existing data. * @param {any} val The value to be assigned to the field. * @chainable */ setData: function(name, val) { var args = (arguments.length > 1) ? [name, val] : [name]; return this._invoke('setData', args); }, /** * @method clearData * @for NodeList * @description Clears data on all Node instances bound to the NodeList. * @param {string} name The name of the field to clear. If no name * is given, all data is cleared. * @chainable */ clearData: function(name) { var args = (arguments.length) ? [name] : []; return this._invoke('clearData', [name]); } }); }, '@VERSION@', {"requires": ["event-base", "node-core", "dom-base"]}); (function () { var GLOBAL_ENV = YUI.Env; if (!GLOBAL_ENV._ready) { GLOBAL_ENV._ready = function() { GLOBAL_ENV.DOMReady = true; GLOBAL_ENV.remove(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready); }; GLOBAL_ENV.add(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready); } })(); YUI.add('event-base', function (Y, NAME) { /* * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * The domready event fires at the moment the browser's DOM is * usable. In most cases, this is before images are fully * downloaded, allowing you to provide a more responsive user * interface. * * In YUI 3, domready subscribers will be notified immediately if * that moment has already passed when the subscription is created. * * One exception is if the yui.js file is dynamically injected into * the page. If this is done, you must tell the YUI instance that * you did this in order for DOMReady (and window load events) to * fire normally. That configuration option is 'injected' -- set * it to true if the yui.js script is not included inline. * * This method is part of the 'event-ready' module, which is a * submodule of 'event'. * * @event domready * @for YUI */ Y.publish('domready', { fireOnce: true, async: true }); if (YUI.Env.DOMReady) { Y.fire('domready'); } else { Y.Do.before(function() { Y.fire('domready'); }, YUI.Env, '_ready'); } /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event * @submodule event-base */ /** * Wraps a DOM event, properties requiring browser abstraction are * fixed here. Provids a security layer when required. * @class DOMEventFacade * @param ev {Event} the DOM event * @param currentTarget {HTMLElement} the element the listener was attached to * @param wrapper {Event.Custom} the custom event wrapper for this DOM event */ var ua = Y.UA, EMPTY = {}, /** * webkit key remapping required for Safari < 3.1 * @property webkitKeymap * @private */ webkitKeymap = { 63232: 38, // up 63233: 40, // down 63234: 37, // left 63235: 39, // right 63276: 33, // page up 63277: 34, // page down 25: 9, // SHIFT-TAB (Safari provides a different key code in // this case, even though the shiftKey modifier is set) 63272: 46, // delete 63273: 36, // home 63275: 35 // end }, /** * Returns a wrapped node. Intended to be used on event targets, * so it will return the node's parent if the target is a text * node. * * If accessing a property of the node throws an error, this is * probably the anonymous div wrapper Gecko adds inside text * nodes. This likely will only occur when attempting to access * the relatedTarget. In this case, we now return null because * the anonymous div is completely useless and we do not know * what the related target was because we can't even get to * the element's parent node. * * @method resolve * @private */ resolve = function(n) { if (!n) { return n; } try { if (n && 3 == n.nodeType) { n = n.parentNode; } } catch(e) { return null; } return Y.one(n); }, DOMEventFacade = function(ev, currentTarget, wrapper) { this._event = ev; this._currentTarget = currentTarget; this._wrapper = wrapper || EMPTY; // if not lazy init this.init(); }; Y.extend(DOMEventFacade, Object, { init: function() { var e = this._event, overrides = this._wrapper.overrides, x = e.pageX, y = e.pageY, c, currentTarget = this._currentTarget; this.altKey = e.altKey; this.ctrlKey = e.ctrlKey; this.metaKey = e.metaKey; this.shiftKey = e.shiftKey; this.type = (overrides && overrides.type) || e.type; this.clientX = e.clientX; this.clientY = e.clientY; this.pageX = x; this.pageY = y; // charCode is unknown in keyup, keydown. keyCode is unknown in keypress. // FF 3.6 - 8+? pass 0 for keyCode in keypress events. // Webkit, FF 3.6-8+?, and IE9+? pass 0 for charCode in keydown, keyup. // Webkit and IE9+? duplicate charCode in keyCode. // Opera never sets charCode, always keyCode (though with the charCode). // IE6-8 don't set charCode or which. // All browsers other than IE6-8 set which=keyCode in keydown, keyup, and // which=charCode in keypress. // // Moral of the story: (e.which || e.keyCode) will always return the // known code for that key event phase. e.keyCode is often different in // keypress from keydown and keyup. c = e.keyCode || e.charCode; if (ua.webkit && (c in webkitKeymap)) { c = webkitKeymap[c]; } this.keyCode = c; this.charCode = c; // Fill in e.which for IE - implementers should always use this over // e.keyCode or e.charCode. this.which = e.which || e.charCode || c; // this.button = e.button; this.button = this.which; this.target = resolve(e.target); this.currentTarget = resolve(currentTarget); this.relatedTarget = resolve(e.relatedTarget); if (e.type == "mousewheel" || e.type == "DOMMouseScroll") { this.wheelDelta = (e.detail) ? (e.detail * -1) : Math.round(e.wheelDelta / 80) || ((e.wheelDelta < 0) ? -1 : 1); } if (this._touch) { this._touch(e, currentTarget, this._wrapper); } }, stopPropagation: function() { this._event.stopPropagation(); this._wrapper.stopped = 1; this.stopped = 1; }, stopImmediatePropagation: function() { var e = this._event; if (e.stopImmediatePropagation) { e.stopImmediatePropagation(); } else { this.stopPropagation(); } this._wrapper.stopped = 2; this.stopped = 2; }, preventDefault: function(returnValue) { var e = this._event; e.preventDefault(); e.returnValue = returnValue || false; this._wrapper.prevented = 1; this.prevented = 1; }, halt: function(immediate) { if (immediate) { this.stopImmediatePropagation(); } else { this.stopPropagation(); } this.preventDefault(); } }); DOMEventFacade.resolve = resolve; Y.DOM2EventFacade = DOMEventFacade; Y.DOMEventFacade = DOMEventFacade; /** * The native event * @property _event * @type {Native DOM Event} * @private */ /** The name of the event (e.g. "click") @property type @type {String} **/ /** `true` if the "alt" or "option" key is pressed. @property altKey @type {Boolean} **/ /** `true` if the shift key is pressed. @property shiftKey @type {Boolean} **/ /** `true` if the "Windows" key on a Windows keyboard, "command" key on an Apple keyboard, or "meta" key on other keyboards is pressed. @property metaKey @type {Boolean} **/ /** `true` if the "Ctrl" or "control" key is pressed. @property ctrlKey @type {Boolean} **/ /** * The X location of the event on the page (including scroll) * @property pageX * @type {Number} */ /** * The Y location of the event on the page (including scroll) * @property pageY * @type {Number} */ /** * The X location of the event in the viewport * @property clientX * @type {Number} */ /** * The Y location of the event in the viewport * @property clientY * @type {Number} */ /** * The keyCode for key events. Uses charCode if keyCode is not available * @property keyCode * @type {Number} */ /** * The charCode for key events. Same as keyCode * @property charCode * @type {Number} */ /** * The button that was pushed. 1 for left click, 2 for middle click, 3 for * right click. This is only reliably populated on `mouseup` events. * @property button * @type {Number} */ /** * The button that was pushed. Same as button. * @property which * @type {Number} */ /** * Node reference for the targeted element * @property target * @type {Node} */ /** * Node reference for the element that the listener was attached to. * @property currentTarget * @type {Node} */ /** * Node reference to the relatedTarget * @property relatedTarget * @type {Node} */ /** * Number representing the direction and velocity of the movement of the mousewheel. * Negative is down, the higher the number, the faster. Applies to the mousewheel event. * @property wheelDelta * @type {Number} */ /** * Stops the propagation to the next bubble target * @method stopPropagation */ /** * Stops the propagation to the next bubble target and * prevents any additional listeners from being exectued * on the current target. * @method stopImmediatePropagation */ /** * Prevents the event's default behavior * @method preventDefault * @param returnValue {string} sets the returnValue of the event to this value * (rather than the default false value). This can be used to add a customized * confirmation query to the beforeunload event). */ /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ (function() { /** * The event utility provides functions to add and remove event listeners, * event cleansing. It also tries to automatically remove listeners it * registers during the unload event. * @module event * @main event * @submodule event-base */ /** * The event utility provides functions to add and remove event listeners, * event cleansing. It also tries to automatically remove listeners it * registers during the unload event. * * @class Event * @static */ Y.Env.evt.dom_wrappers = {}; Y.Env.evt.dom_map = {}; var YDOM = Y.DOM, _eventenv = Y.Env.evt, config = Y.config, win = config.win, add = YUI.Env.add, remove = YUI.Env.remove, onLoad = function() { YUI.Env.windowLoaded = true; Y.Event._load(); remove(win, "load", onLoad); }, onUnload = function() { Y.Event._unload(); }, EVENT_READY = 'domready', COMPAT_ARG = '~yui|2|compat~', shouldIterate = function(o) { try { // TODO: See if there's a more performant way to return true early on this, for the common case return (o && typeof o !== "string" && Y.Lang.isNumber(o.length) && !o.tagName && !YDOM.isWindow(o)); } catch(ex) { return false; } }, // aliases to support DOM event subscription clean up when the last // subscriber is detached. deleteAndClean overrides the DOM event's wrapper // CustomEvent _delete method. _ceProtoDelete = Y.CustomEvent.prototype._delete, _deleteAndClean = function(s) { var ret = _ceProtoDelete.apply(this, arguments); if (!this.hasSubs()) { Y.Event._clean(this); } return ret; }, Event = function() { /** * True after the onload event has fired * @property _loadComplete * @type boolean * @static * @private */ var _loadComplete = false, /** * The number of times to poll after window.onload. This number is * increased if additional late-bound handlers are requested after * the page load. * @property _retryCount * @static * @private */ _retryCount = 0, /** * onAvailable listeners * @property _avail * @static * @private */ _avail = [], /** * Custom event wrappers for DOM events. Key is * 'event:' + Element uid stamp + event type * @property _wrappers * @type Y.Event.Custom * @static * @private */ _wrappers = _eventenv.dom_wrappers, _windowLoadKey = null, /** * Custom event wrapper map DOM events. Key is * Element uid stamp. Each item is a hash of custom event * wrappers as provided in the _wrappers collection. This * provides the infrastructure for getListeners. * @property _el_events * @static * @private */ _el_events = _eventenv.dom_map; return { /** * The number of times we should look for elements that are not * in the DOM at the time the event is requested after the document * has been loaded. The default is 1000@amp;40 ms, so it will poll * for 40 seconds or until all outstanding handlers are bound * (whichever comes first). * @property POLL_RETRYS * @type int * @static * @final */ POLL_RETRYS: 1000, /** * The poll interval in milliseconds * @property POLL_INTERVAL * @type int * @static * @final */ POLL_INTERVAL: 40, /** * addListener/removeListener can throw errors in unexpected scenarios. * These errors are suppressed, the method returns false, and this property * is set * @property lastError * @static * @type Error */ lastError: null, /** * poll handle * @property _interval * @static * @private */ _interval: null, /** * document readystate poll handle * @property _dri * @static * @private */ _dri: null, /** * True when the document is initially usable * @property DOMReady * @type boolean * @static */ DOMReady: false, /** * @method startInterval * @static * @private */ startInterval: function() { if (!Event._interval) { Event._interval = setInterval(Event._poll, Event.POLL_INTERVAL); } }, /** * Executes the supplied callback when the item with the supplied * id is found. This is meant to be used to execute behavior as * soon as possible as the page loads. If you use this after the * initial page load it will poll for a fixed time for the element. * The number of times it will poll and the frequency are * configurable. By default it will poll for 10 seconds. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onAvailable * * @param {string||string[]} id the id of the element, or an array * of ids to look for. * @param {function} fn what to execute when the element is found. * @param {object} p_obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} p_override If set to true, fn will execute * in the context of p_obj, if set to an object it * will execute in the context of that object * @param checkContent {boolean} check child node readiness (onContentReady) * @static * @deprecated Use Y.on("available") */ // @TODO fix arguments onAvailable: function(id, fn, p_obj, p_override, checkContent, compat) { var a = Y.Array(id), i, availHandle; for (i=0; i<a.length; i=i+1) { _avail.push({ id: a[i], fn: fn, obj: p_obj, override: p_override, checkReady: checkContent, compat: compat }); } _retryCount = this.POLL_RETRYS; // We want the first test to be immediate, but async setTimeout(Event._poll, 0); availHandle = new Y.EventHandle({ _delete: function() { // set by the event system for lazy DOM listeners if (availHandle.handle) { availHandle.handle.detach(); return; } var i, j; // otherwise try to remove the onAvailable listener(s) for (i = 0; i < a.length; i++) { for (j = 0; j < _avail.length; j++) { if (a[i] === _avail[j].id) { _avail.splice(j, 1); } } } } }); return availHandle; }, /** * Works the same way as onAvailable, but additionally checks the * state of sibling elements to determine if the content of the * available element is safe to modify. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onContentReady * * @param {string} id the id of the element to look for. * @param {function} fn what to execute when the element is ready. * @param {object} obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} override If set to true, fn will execute * in the context of p_obj. If an object, fn will * exectute in the context of that object * * @static * @deprecated Use Y.on("contentready") */ // @TODO fix arguments onContentReady: function(id, fn, obj, override, compat) { return Event.onAvailable(id, fn, obj, override, true, compat); }, /** * Adds an event listener * * @method attach * * @param {String} type The type of event to append * @param {Function} fn The method the event invokes * @param {String|HTMLElement|Array|NodeList} el An id, an element * reference, or a collection of ids and/or elements to assign the * listener to. * @param {Object} context optional context object * @param {Boolean|object} args 0..n arguments to pass to the callback * @return {EventHandle} an object to that can be used to detach the listener * * @static */ attach: function(type, fn, el, context) { return Event._attach(Y.Array(arguments, 0, true)); }, _createWrapper: function (el, type, capture, compat, facade) { var cewrapper, ek = Y.stamp(el), key = 'event:' + ek + type; if (false === facade) { key += 'native'; } if (capture) { key += 'capture'; } cewrapper = _wrappers[key]; if (!cewrapper) { // create CE wrapper cewrapper = Y.publish(key, { silent: true, bubbles: false, contextFn: function() { if (compat) { return cewrapper.el; } else { cewrapper.nodeRef = cewrapper.nodeRef || Y.one(cewrapper.el); return cewrapper.nodeRef; } } }); cewrapper.overrides = {}; // for later removeListener calls cewrapper.el = el; cewrapper.key = key; cewrapper.domkey = ek; cewrapper.type = type; cewrapper.fn = function(e) { cewrapper.fire(Event.getEvent(e, el, (compat || (false === facade)))); }; cewrapper.capture = capture; if (el == win && type == "load") { // window load happens once cewrapper.fireOnce = true; _windowLoadKey = key; } cewrapper._delete = _deleteAndClean; _wrappers[key] = cewrapper; _el_events[ek] = _el_events[ek] || {}; _el_events[ek][key] = cewrapper; add(el, type, cewrapper.fn, capture); } return cewrapper; }, _attach: function(args, conf) { var compat, handles, oEl, cewrapper, context, fireNow = false, ret, type = args[0], fn = args[1], el = args[2] || win, facade = conf && conf.facade, capture = conf && conf.capture, overrides = conf && conf.overrides; if (args[args.length-1] === COMPAT_ARG) { compat = true; } if (!fn || !fn.call) { // throw new TypeError(type + " attach call failed, callback undefined"); return false; } // The el argument can be an array of elements or element ids. if (shouldIterate(el)) { handles=[]; Y.each(el, function(v, k) { args[2] = v; handles.push(Event._attach(args.slice(), conf)); }); // return (handles.length === 1) ? handles[0] : handles; return new Y.EventHandle(handles); // If the el argument is a string, we assume it is // actually the id of the element. If the page is loaded // we convert el to the actual element, otherwise we // defer attaching the event until the element is // ready } else if (Y.Lang.isString(el)) { // oEl = (compat) ? Y.DOM.byId(el) : Y.Selector.query(el); if (compat) { oEl = YDOM.byId(el); } else { oEl = Y.Selector.query(el); switch (oEl.length) { case 0: oEl = null; break; case 1: oEl = oEl[0]; break; default: args[2] = oEl; return Event._attach(args, conf); } } if (oEl) { el = oEl; // Not found = defer adding the event until the element is available } else { ret = Event.onAvailable(el, function() { ret.handle = Event._attach(args, conf); }, Event, true, false, compat); return ret; } } // Element should be an html element or node if (!el) { return false; } if (Y.Node && Y.instanceOf(el, Y.Node)) { el = Y.Node.getDOMNode(el); } cewrapper = Event._createWrapper(el, type, capture, compat, facade); if (overrides) { Y.mix(cewrapper.overrides, overrides); } if (el == win && type == "load") { // if the load is complete, fire immediately. // all subscribers, including the current one // will be notified. if (YUI.Env.windowLoaded) { fireNow = true; } } if (compat) { args.pop(); } context = args[3]; // set context to the Node if not specified // ret = cewrapper.on.apply(cewrapper, trimmedArgs); ret = cewrapper._on(fn, context, (args.length > 4) ? args.slice(4) : null); if (fireNow) { cewrapper.fire(); } return ret; }, /** * Removes an event listener. Supports the signature the event was bound * with, but the preferred way to remove listeners is using the handle * that is returned when using Y.on * * @method detach * * @param {String} type the type of event to remove. * @param {Function} fn the method the event invokes. If fn is * undefined, then all event handlers for the type of event are * removed. * @param {String|HTMLElement|Array|NodeList|EventHandle} el An * event handle, an id, an element reference, or a collection * of ids and/or elements to remove the listener from. * @return {boolean} true if the unbind was successful, false otherwise. * @static */ detach: function(type, fn, el, obj) { var args=Y.Array(arguments, 0, true), compat, l, ok, i, id, ce; if (args[args.length-1] === COMPAT_ARG) { compat = true; // args.pop(); } if (type && type.detach) { return type.detach(); } // The el argument can be a string if (typeof el == "string") { // el = (compat) ? Y.DOM.byId(el) : Y.all(el); if (compat) { el = YDOM.byId(el); } else { el = Y.Selector.query(el); l = el.length; if (l < 1) { el = null; } else if (l == 1) { el = el[0]; } } // return Event.detach.apply(Event, args); } if (!el) { return false; } if (el.detach) { args.splice(2, 1); return el.detach.apply(el, args); // The el argument can be an array of elements or element ids. } else if (shouldIterate(el)) { ok = true; for (i=0, l=el.length; i<l; ++i) { args[2] = el[i]; ok = ( Y.Event.detach.apply(Y.Event, args) && ok ); } return ok; } if (!type || !fn || !fn.call) { return Event.purgeElement(el, false, type); } id = 'event:' + Y.stamp(el) + type; ce = _wrappers[id]; if (ce) { return ce.detach(fn); } else { return false; } }, /** * Finds the event in the window object, the caller's arguments, or * in the arguments of another method in the callstack. This is * executed automatically for events registered through the event * manager, so the implementer should not normally need to execute * this function at all. * @method getEvent * @param {Event} e the event parameter from the handler * @param {HTMLElement} el the element the listener was attached to * @return {Event} the event * @static */ getEvent: function(e, el, noFacade) { var ev = e || win.event; return (noFacade) ? ev : new Y.DOMEventFacade(ev, el, _wrappers['event:' + Y.stamp(el) + e.type]); }, /** * Generates an unique ID for the element if it does not already * have one. * @method generateId * @param el the element to create the id for * @return {string} the resulting id of the element * @static */ generateId: function(el) { return YDOM.generateID(el); }, /** * We want to be able to use getElementsByTagName as a collection * to attach a group of events to. Unfortunately, different * browsers return different types of collections. This function * tests to determine if the object is array-like. It will also * fail if the object is an array, but is empty. * @method _isValidCollection * @param o the object to test * @return {boolean} true if the object is array-like and populated * @deprecated was not meant to be used directly * @static * @private */ _isValidCollection: shouldIterate, /** * hook up any deferred listeners * @method _load * @static * @private */ _load: function(e) { if (!_loadComplete) { _loadComplete = true; // Just in case DOMReady did not go off for some reason // E._ready(); if (Y.fire) { Y.fire(EVENT_READY); } // Available elements may not have been detected before the // window load event fires. Try to find them now so that the // the user is more likely to get the onAvailable notifications // before the window load notification Event._poll(); } }, /** * Polling function that runs before the onload event fires, * attempting to attach to DOM Nodes as soon as they are * available * @method _poll * @static * @private */ _poll: function() { if (Event.locked) { return; } if (Y.UA.ie && !YUI.Env.DOMReady) { // Hold off if DOMReady has not fired and check current // readyState to protect against the IE operation aborted // issue. Event.startInterval(); return; } Event.locked = true; // keep trying until after the page is loaded. We need to // check the page load state prior to trying to bind the // elements so that we can be certain all elements have been // tested appropriately var i, len, item, el, notAvail, executeItem, tryAgain = !_loadComplete; if (!tryAgain) { tryAgain = (_retryCount > 0); } // onAvailable notAvail = []; executeItem = function (el, item) { var context, ov = item.override; try { if (item.compat) { if (item.override) { if (ov === true) { context = item.obj; } else { context = ov; } } else { context = el; } item.fn.call(context, item.obj); } else { context = item.obj || Y.one(el); item.fn.apply(context, (Y.Lang.isArray(ov)) ? ov : []); } } catch (e) { } }; // onAvailable for (i=0,len=_avail.length; i<len; ++i) { item = _avail[i]; if (item && !item.checkReady) { // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id); el = (item.compat) ? YDOM.byId(item.id) : Y.Selector.query(item.id, null, true); if (el) { executeItem(el, item); _avail[i] = null; } else { notAvail.push(item); } } } // onContentReady for (i=0,len=_avail.length; i<len; ++i) { item = _avail[i]; if (item && item.checkReady) { // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id); el = (item.compat) ? YDOM.byId(item.id) : Y.Selector.query(item.id, null, true); if (el) { // The element is available, but not necessarily ready // @todo should we test parentNode.nextSibling? if (_loadComplete || (el.get && el.get('nextSibling')) || el.nextSibling) { executeItem(el, item); _avail[i] = null; } } else { notAvail.push(item); } } } _retryCount = (notAvail.length === 0) ? 0 : _retryCount - 1; if (tryAgain) { // we may need to strip the nulled out items here Event.startInterval(); } else { clearInterval(Event._interval); Event._interval = null; } Event.locked = false; return; }, /** * Removes all listeners attached to the given element via addListener. * Optionally, the node's children can also be purged. * Optionally, you can specify a specific type of event to remove. * @method purgeElement * @param {HTMLElement} el the element to purge * @param {boolean} recurse recursively purge this element's children * as well. Use with caution. * @param {string} type optional type of listener to purge. If * left out, all listeners will be removed * @static */ purgeElement: function(el, recurse, type) { // var oEl = (Y.Lang.isString(el)) ? Y.one(el) : el, var oEl = (Y.Lang.isString(el)) ? Y.Selector.query(el, null, true) : el, lis = Event.getListeners(oEl, type), i, len, children, child; if (recurse && oEl) { lis = lis || []; children = Y.Selector.query('*', oEl); len = children.length; for (i = 0; i < len; ++i) { child = Event.getListeners(children[i], type); if (child) { lis = lis.concat(child); } } } if (lis) { for (i = 0, len = lis.length; i < len; ++i) { lis[i].detachAll(); } } }, /** * Removes all object references and the DOM proxy subscription for * a given event for a DOM node. * * @method _clean * @param wrapper {CustomEvent} Custom event proxy for the DOM * subscription * @private * @static * @since 3.4.0 */ _clean: function (wrapper) { var key = wrapper.key, domkey = wrapper.domkey; remove(wrapper.el, wrapper.type, wrapper.fn, wrapper.capture); delete _wrappers[key]; delete Y._yuievt.events[key]; if (_el_events[domkey]) { delete _el_events[domkey][key]; if (!Y.Object.size(_el_events[domkey])) { delete _el_events[domkey]; } } }, /** * Returns all listeners attached to the given element via addListener. * Optionally, you can specify a specific type of event to return. * @method getListeners * @param el {HTMLElement|string} the element or element id to inspect * @param type {string} optional type of listener to return. If * left out, all listeners will be returned * @return {CustomEvent} the custom event wrapper for the DOM event(s) * @static */ getListeners: function(el, type) { var ek = Y.stamp(el, true), evts = _el_events[ek], results=[] , key = (type) ? 'event:' + ek + type : null, adapters = _eventenv.plugins; if (!evts) { return null; } if (key) { // look for synthetic events if (adapters[type] && adapters[type].eventDef) { key += '_synth'; } if (evts[key]) { results.push(evts[key]); } // get native events as well key += 'native'; if (evts[key]) { results.push(evts[key]); } } else { Y.each(evts, function(v, k) { results.push(v); }); } return (results.length) ? results : null; }, /** * Removes all listeners registered by pe.event. Called * automatically during the unload event. * @method _unload * @static * @private */ _unload: function(e) { Y.each(_wrappers, function(v, k) { if (v.type == 'unload') { v.fire(e); } v.detachAll(); }); remove(win, "unload", onUnload); }, /** * Adds a DOM event directly without the caching, cleanup, context adj, etc * * @method nativeAdd * @param {HTMLElement} el the element to bind the handler to * @param {string} type the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ nativeAdd: add, /** * Basic remove listener * * @method nativeRemove * @param {HTMLElement} el the element to bind the handler to * @param {string} type the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ nativeRemove: remove }; }(); Y.Event = Event; if (config.injected || YUI.Env.windowLoaded) { onLoad(); } else { add(win, "load", onLoad); } // Process onAvailable/onContentReady items when when the DOM is ready in IE if (Y.UA.ie) { Y.on(EVENT_READY, Event._poll); } try { add(win, "unload", onUnload); } catch(e) { } Event.Custom = Y.CustomEvent; Event.Subscriber = Y.Subscriber; Event.Target = Y.EventTarget; Event.Handle = Y.EventHandle; Event.Facade = Y.EventFacade; Event._poll(); }()); /** * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * Executes the callback as soon as the specified element * is detected in the DOM. This function expects a selector * string for the element(s) to detect. If you already have * an element reference, you don't need this event. * @event available * @param type {string} 'available' * @param fn {function} the callback function to execute. * @param el {string} an selector for the element(s) to attach * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.available = { on: function(type, fn, id, o) { var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null; return Y.Event.onAvailable.call(Y.Event, id, fn, o, a); } }; /** * Executes the callback as soon as the specified element * is detected in the DOM with a nextSibling property * (indicating that the element's children are available). * This function expects a selector * string for the element(s) to detect. If you already have * an element reference, you don't need this event. * @event contentready * @param type {string} 'contentready' * @param fn {function} the callback function to execute. * @param el {string} an selector for the element(s) to attach. * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.contentready = { on: function(type, fn, id, o) { var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null; return Y.Event.onContentReady.call(Y.Event, id, fn, o, a); } }; }, '@VERSION@', {"requires": ["event-custom-base"]}); (function() { var stateChangeListener, GLOBAL_ENV = YUI.Env, config = YUI.config, doc = config.doc, docElement = doc && doc.documentElement, EVENT_NAME = 'onreadystatechange', pollInterval = config.pollInterval || 40; if (docElement.doScroll && !GLOBAL_ENV._ieready) { GLOBAL_ENV._ieready = function() { GLOBAL_ENV._ready(); }; /*! DOMReady: based on work by: Dean Edwards/John Resig/Matthias Miller/Diego Perini */ // Internet Explorer: use the doScroll() method on the root element. // This isolates what appears to be a safe moment to manipulate the // DOM prior to when the document's readyState suggests it is safe to do so. if (self !== self.top) { stateChangeListener = function() { if (doc.readyState == 'complete') { GLOBAL_ENV.remove(doc, EVENT_NAME, stateChangeListener); GLOBAL_ENV.ieready(); } }; GLOBAL_ENV.add(doc, EVENT_NAME, stateChangeListener); } else { GLOBAL_ENV._dri = setInterval(function() { try { docElement.doScroll('left'); clearInterval(GLOBAL_ENV._dri); GLOBAL_ENV._dri = null; GLOBAL_ENV._ieready(); } catch (domNotReady) { } }, pollInterval); } } })(); YUI.add('event-base-ie', function (Y, NAME) { /* * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event * @submodule event-base */ function IEEventFacade() { // IEEventFacade.superclass.constructor.apply(this, arguments); Y.DOM2EventFacade.apply(this, arguments); } /* * (intentially left out of API docs) * Alternate Facade implementation that is based on Object.defineProperty, which * is partially supported in IE8. Properties that involve setup work are * deferred to temporary getters using the static _define method. */ function IELazyFacade(e) { var proxy = Y.config.doc.createEventObject(e), proto = IELazyFacade.prototype; // TODO: necessary? proxy.hasOwnProperty = function () { return true; }; proxy.init = proto.init; proxy.halt = proto.halt; proxy.preventDefault = proto.preventDefault; proxy.stopPropagation = proto.stopPropagation; proxy.stopImmediatePropagation = proto.stopImmediatePropagation; Y.DOM2EventFacade.apply(proxy, arguments); return proxy; } var imp = Y.config.doc && Y.config.doc.implementation, useLazyFacade = Y.config.lazyEventFacade, buttonMap = { 0: 1, // left click 4: 2, // middle click 2: 3 // right click }, relatedTargetMap = { mouseout: 'toElement', mouseover: 'fromElement' }, resolve = Y.DOM2EventFacade.resolve, proto = { init: function() { IEEventFacade.superclass.init.apply(this, arguments); var e = this._event, x, y, d, b, de, t; this.target = resolve(e.srcElement); if (('clientX' in e) && (!x) && (0 !== x)) { x = e.clientX; y = e.clientY; d = Y.config.doc; b = d.body; de = d.documentElement; x += (de.scrollLeft || (b && b.scrollLeft) || 0); y += (de.scrollTop || (b && b.scrollTop) || 0); this.pageX = x; this.pageY = y; } if (e.type == "mouseout") { t = e.toElement; } else if (e.type == "mouseover") { t = e.fromElement; } // fallback to t.relatedTarget to support simulated events. // IE doesn't support setting toElement or fromElement on generic // events, so Y.Event.simulate sets relatedTarget instead. this.relatedTarget = resolve(t || e.relatedTarget); // which should contain the unicode key code if this is a key event. // For click events, which is normalized for which mouse button was // clicked. this.which = // chained assignment this.button = e.keyCode || buttonMap[e.button] || e.button; }, stopPropagation: function() { this._event.cancelBubble = true; this._wrapper.stopped = 1; this.stopped = 1; }, stopImmediatePropagation: function() { this.stopPropagation(); this._wrapper.stopped = 2; this.stopped = 2; }, preventDefault: function(returnValue) { this._event.returnValue = returnValue || false; this._wrapper.prevented = 1; this.prevented = 1; } }; Y.extend(IEEventFacade, Y.DOM2EventFacade, proto); Y.extend(IELazyFacade, Y.DOM2EventFacade, proto); IELazyFacade.prototype.init = function () { var e = this._event, overrides = this._wrapper.overrides, define = IELazyFacade._define, lazyProperties = IELazyFacade._lazyProperties, prop; this.altKey = e.altKey; this.ctrlKey = e.ctrlKey; this.metaKey = e.metaKey; this.shiftKey = e.shiftKey; this.type = (overrides && overrides.type) || e.type; this.clientX = e.clientX; this.clientY = e.clientY; this.keyCode = // chained assignment this.charCode = e.keyCode; this.which = // chained assignment this.button = e.keyCode || buttonMap[e.button] || e.button; for (prop in lazyProperties) { if (lazyProperties.hasOwnProperty(prop)) { define(this, prop, lazyProperties[prop]); } } if (this._touch) { this._touch(e, this._currentTarget, this._wrapper); } }; IELazyFacade._lazyProperties = { target: function () { return resolve(this._event.srcElement); }, relatedTarget: function () { var e = this._event, targetProp = relatedTargetMap[e.type] || 'relatedTarget'; // fallback to t.relatedTarget to support simulated events. // IE doesn't support setting toElement or fromElement on generic // events, so Y.Event.simulate sets relatedTarget instead. return resolve(e[targetProp] || e.relatedTarget); }, currentTarget: function () { return resolve(this._currentTarget); }, wheelDelta: function () { var e = this._event; if (e.type === "mousewheel" || e.type === "DOMMouseScroll") { return (e.detail) ? (e.detail * -1) : // wheelDelta between -80 and 80 result in -1 or 1 Math.round(e.wheelDelta / 80) || ((e.wheelDelta < 0) ? -1 : 1); } }, pageX: function () { var e = this._event, val = e.pageX, doc, bodyScroll, docScroll; if (val === undefined) { doc = Y.config.doc; bodyScroll = doc.body && doc.body.scrollLeft; docScroll = doc.documentElement.scrollLeft; val = e.clientX + (docScroll || bodyScroll || 0); } return val; }, pageY: function () { var e = this._event, val = e.pageY, doc, bodyScroll, docScroll; if (val === undefined) { doc = Y.config.doc; bodyScroll = doc.body && doc.body.scrollTop; docScroll = doc.documentElement.scrollTop; val = e.clientY + (docScroll || bodyScroll || 0); } return val; } }; /** * Wrapper function for Object.defineProperty that creates a property whose * value will be calulated only when asked for. After calculating the value, * the getter wll be removed, so it will behave as a normal property beyond that * point. A setter is also assigned so assigning to the property will clear * the getter, so foo.prop = 'a'; foo.prop; won't trigger the getter, * overwriting value 'a'. * * Used only by the DOMEventFacades used by IE8 when the YUI configuration * <code>lazyEventFacade</code> is set to true. * * @method _define * @param o {DOMObject} A DOM object to add the property to * @param prop {String} The name of the new property * @param valueFn {Function} The function that will return the initial, default * value for the property. * @static * @private */ IELazyFacade._define = function (o, prop, valueFn) { function val(v) { var ret = (arguments.length) ? v : valueFn.call(this); delete o[prop]; Object.defineProperty(o, prop, { value: ret, configurable: true, writable: true }); return ret; } Object.defineProperty(o, prop, { get: val, set: val, configurable: true }); }; if (imp && (!imp.hasFeature('Events', '2.0'))) { if (useLazyFacade) { // Make sure we can use the lazy facade logic try { Object.defineProperty(Y.config.doc.createEventObject(), 'z', {}); } catch (e) { useLazyFacade = false; } } Y.DOMEventFacade = (useLazyFacade) ? IELazyFacade : IEEventFacade; } }, '@VERSION@', {"requires": ["node-base"]}); YUI.add('pluginhost-base', function (Y, NAME) { /** * Provides the augmentable PluginHost interface, which can be added to any class. * @module pluginhost */ /** * Provides the augmentable PluginHost interface, which can be added to any class. * @module pluginhost-base */ /** * <p> * An augmentable class, which provides the augmented class with the ability to host plugins. * It adds <a href="#method_plug">plug</a> and <a href="#method_unplug">unplug</a> methods to the augmented class, which can * be used to add or remove plugins from instances of the class. * </p> * * <p>Plugins can also be added through the constructor configuration object passed to the host class' constructor using * the "plugins" property. Supported values for the "plugins" property are those defined by the <a href="#method_plug">plug</a> method. * * For example the following code would add the AnimPlugin and IOPlugin to Overlay (the plugin host): * <xmp> * var o = new Overlay({plugins: [ AnimPlugin, {fn:IOPlugin, cfg:{section:"header"}}]}); * </xmp> * </p> * <p> * Plug.Host's protected <a href="#method_initPlugins">_initPlugins</a> and <a href="#method_destroyPlugins">_destroyPlugins</a> * methods should be invoked by the host class at the appropriate point in the host's lifecyle. * </p> * * @class Plugin.Host */ var L = Y.Lang; function PluginHost() { this._plugins = {}; } PluginHost.prototype = { /** * Adds a plugin to the host object. This will instantiate the * plugin and attach it to the configured namespace on the host object. * * @method plug * @chainable * @param P {Function | Object |Array} Accepts the plugin class, or an * object with a "fn" property specifying the plugin class and * a "cfg" property specifying the configuration for the Plugin. * <p> * Additionally an Array can also be passed in, with the above function or * object values, allowing the user to add multiple plugins in a single call. * </p> * @param config (Optional) If the first argument is the plugin class, the second argument * can be the configuration for the plugin. * @return {Base} A reference to the host object */ plug: function(Plugin, config) { var i, ln, ns; if (L.isArray(Plugin)) { for (i = 0, ln = Plugin.length; i < ln; i++) { this.plug(Plugin[i]); } } else { if (Plugin && !L.isFunction(Plugin)) { config = Plugin.cfg; Plugin = Plugin.fn; } // Plugin should be fn by now if (Plugin && Plugin.NS) { ns = Plugin.NS; config = config || {}; config.host = this; if (this.hasPlugin(ns)) { // Update config if (this[ns].setAttrs) { this[ns].setAttrs(config); } } else { // Create new instance this[ns] = new Plugin(config); this._plugins[ns] = Plugin; } } } return this; }, /** * Removes a plugin from the host object. This will destroy the * plugin instance and delete the namespace from the host object. * * @method unplug * @param {String | Function} plugin The namespace of the plugin, or the plugin class with the static NS namespace property defined. If not provided, * all registered plugins are unplugged. * @return {Base} A reference to the host object * @chainable */ unplug: function(plugin) { var ns = plugin, plugins = this._plugins; if (plugin) { if (L.isFunction(plugin)) { ns = plugin.NS; if (ns && (!plugins[ns] || plugins[ns] !== plugin)) { ns = null; } } if (ns) { if (this[ns]) { if (this[ns].destroy) { this[ns].destroy(); } delete this[ns]; } if (plugins[ns]) { delete plugins[ns]; } } } else { for (ns in this._plugins) { if (this._plugins.hasOwnProperty(ns)) { this.unplug(ns); } } } return this; }, /** * Determines if a plugin has plugged into this host. * * @method hasPlugin * @param {String} ns The plugin's namespace * @return {Plugin} Returns a truthy value (the plugin instance) if present, or undefined if not. */ hasPlugin : function(ns) { return (this._plugins[ns] && this[ns]); }, /** * Initializes static plugins registered on the host (using the * Base.plug static method) and any plugins passed to the * instance through the "plugins" configuration property. * * @method _initPlugins * @param {Config} config The configuration object with property name/value pairs. * @private */ _initPlugins: function(config) { this._plugins = this._plugins || {}; if (this._initConfigPlugins) { this._initConfigPlugins(config); } }, /** * Unplugs and destroys all plugins on the host * @method _destroyPlugins * @private */ _destroyPlugins: function() { this.unplug(); } }; Y.namespace("Plugin").Host = PluginHost; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('pluginhost-config', function (Y, NAME) { /** * Adds pluginhost constructor configuration and static configuration support * @submodule pluginhost-config */ var PluginHost = Y.Plugin.Host, L = Y.Lang; /** * A protected initialization method, used by the host class to initialize * plugin configurations passed the constructor, through the config object. * * Host objects should invoke this method at the appropriate time in their * construction lifecycle. * * @method _initConfigPlugins * @param {Object} config The configuration object passed to the constructor * @protected * @for Plugin.Host */ PluginHost.prototype._initConfigPlugins = function(config) { // Class Configuration var classes = (this._getClasses) ? this._getClasses() : [this.constructor], plug = [], unplug = {}, constructor, i, classPlug, classUnplug, pluginClassName; // TODO: Room for optimization. Can we apply statically/unplug in same pass? for (i = classes.length - 1; i >= 0; i--) { constructor = classes[i]; classUnplug = constructor._UNPLUG; if (classUnplug) { // subclasses over-write Y.mix(unplug, classUnplug, true); } classPlug = constructor._PLUG; if (classPlug) { // subclasses over-write Y.mix(plug, classPlug, true); } } for (pluginClassName in plug) { if (plug.hasOwnProperty(pluginClassName)) { if (!unplug[pluginClassName]) { this.plug(plug[pluginClassName]); } } } // User Configuration if (config && config.plugins) { this.plug(config.plugins); } }; /** * Registers plugins to be instantiated at the class level (plugins * which should be plugged into every instance of the class by default). * * @method plug * @static * * @param {Function} hostClass The host class on which to register the plugins * @param {Function | Array} plugin Either the plugin class, an array of plugin classes or an array of objects (with fn and cfg properties defined) * @param {Object} config (Optional) If plugin is the plugin class, the configuration for the plugin * @for Plugin.Host */ PluginHost.plug = function(hostClass, plugin, config) { // Cannot plug into Base, since Plugins derive from Base [ will cause infinite recurrsion ] var p, i, l, name; if (hostClass !== Y.Base) { hostClass._PLUG = hostClass._PLUG || {}; if (!L.isArray(plugin)) { if (config) { plugin = {fn:plugin, cfg:config}; } plugin = [plugin]; } for (i = 0, l = plugin.length; i < l;i++) { p = plugin[i]; name = p.NAME || p.fn.NAME; hostClass._PLUG[name] = p; } } }; /** * Unregisters any class level plugins which have been registered by the host class, or any * other class in the hierarchy. * * @method unplug * @static * * @param {Function} hostClass The host class from which to unregister the plugins * @param {Function | Array} plugin The plugin class, or an array of plugin classes * @for Plugin.Host */ PluginHost.unplug = function(hostClass, plugin) { var p, i, l, name; if (hostClass !== Y.Base) { hostClass._UNPLUG = hostClass._UNPLUG || {}; if (!L.isArray(plugin)) { plugin = [plugin]; } for (i = 0, l = plugin.length; i < l; i++) { p = plugin[i]; name = p.NAME; if (!hostClass._PLUG[name]) { hostClass._UNPLUG[name] = p; } else { delete hostClass._PLUG[name]; } } } }; }, '@VERSION@', {"requires": ["pluginhost-base"]}); YUI.add('event-delegate', function (Y, NAME) { /** * Adds event delegation support to the library. * * @module event * @submodule event-delegate */ var toArray = Y.Array, YLang = Y.Lang, isString = YLang.isString, isObject = YLang.isObject, isArray = YLang.isArray, selectorTest = Y.Selector.test, detachCategories = Y.Env.evt.handles; /** * <p>Sets up event delegation on a container element. The delegated event * will use a supplied selector or filtering function to test if the event * references at least one node that should trigger the subscription * callback.</p> * * <p>Selector string filters will trigger the callback if the event originated * from a node that matches it or is contained in a node that matches it. * Function filters are called for each Node up the parent axis to the * subscribing container node, and receive at each level the Node and the event * object. The function should return true (or a truthy value) if that Node * should trigger the subscription callback. Note, it is possible for filters * to match multiple Nodes for a single event. In this case, the delegate * callback will be executed for each matching Node.</p> * * <p>For each matching Node, the callback will be executed with its 'this' * object set to the Node matched by the filter (unless a specific context was * provided during subscription), and the provided event's * <code>currentTarget</code> will also be set to the matching Node. The * containing Node from which the subscription was originally made can be * referenced as <code>e.container</code>. * * @method delegate * @param type {String} the event type to delegate * @param fn {Function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param el {String|node} the element that is the delegation container * @param filter {string|Function} a selector that must match the target of the * event or a function to test target and its parents for a match * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @static * @for Event */ function delegate(type, fn, el, filter) { var args = toArray(arguments, 0, true), query = isString(el) ? el : null, typeBits, synth, container, categories, cat, i, len, handles, handle; // Support Y.delegate({ click: fnA, key: fnB }, el, filter, ...); // and Y.delegate(['click', 'key'], fn, el, filter, ...); if (isObject(type)) { handles = []; if (isArray(type)) { for (i = 0, len = type.length; i < len; ++i) { args[0] = type[i]; handles.push(Y.delegate.apply(Y, args)); } } else { // Y.delegate({'click', fn}, el, filter) => // Y.delegate('click', fn, el, filter) args.unshift(null); // one arg becomes two; need to make space for (i in type) { if (type.hasOwnProperty(i)) { args[0] = i; args[1] = type[i]; handles.push(Y.delegate.apply(Y, args)); } } } return new Y.EventHandle(handles); } typeBits = type.split(/\|/); if (typeBits.length > 1) { cat = typeBits.shift(); args[0] = type = typeBits.shift(); } synth = Y.Node.DOM_EVENTS[type]; if (isObject(synth) && synth.delegate) { handle = synth.delegate.apply(synth, arguments); } if (!handle) { if (!type || !fn || !el || !filter) { return; } container = (query) ? Y.Selector.query(query, null, true) : el; if (!container && isString(el)) { handle = Y.on('available', function () { Y.mix(handle, Y.delegate.apply(Y, args), true); }, el); } if (!handle && container) { args.splice(2, 2, container); // remove the filter handle = Y.Event._attach(args, { facade: false }); handle.sub.filter = filter; handle.sub._notify = delegate.notifySub; } } if (handle && cat) { categories = detachCategories[cat] || (detachCategories[cat] = {}); categories = categories[type] || (categories[type] = []); categories.push(handle); } return handle; } /** Overrides the <code>_notify</code> method on the normal DOM subscription to inject the filtering logic and only proceed in the case of a match. This method is hosted as a private property of the `delegate` method (e.g. `Y.delegate.notifySub`) @method notifySub @param thisObj {Object} default 'this' object for the callback @param args {Array} arguments passed to the event's <code>fire()</code> @param ce {CustomEvent} the custom event managing the DOM subscriptions for the subscribed event on the subscribing node. @return {Boolean} false if the event was stopped @private @static @since 3.2.0 **/ delegate.notifySub = function (thisObj, args, ce) { // Preserve args for other subscribers args = args.slice(); if (this.args) { args.push.apply(args, this.args); } // Only notify subs if the event occurred on a targeted element var currentTarget = delegate._applyFilter(this.filter, args, ce), //container = e.currentTarget, e, i, len, ret; if (currentTarget) { // Support multiple matches up the the container subtree currentTarget = toArray(currentTarget); // The second arg is the currentTarget, but we'll be reusing this // facade, replacing the currentTarget for each use, so it doesn't // matter what element we seed it with. e = args[0] = new Y.DOMEventFacade(args[0], ce.el, ce); e.container = Y.one(ce.el); for (i = 0, len = currentTarget.length; i < len && !e.stopped; ++i) { e.currentTarget = Y.one(currentTarget[i]); ret = this.fn.apply(this.context || e.currentTarget, args); if (ret === false) { // stop further notifications break; } } return ret; } }; /** Compiles a selector string into a filter function to identify whether Nodes along the parent axis of an event's target should trigger event notification. This function is memoized, so previously compiled filter functions are returned if the same selector string is provided. This function may be useful when defining synthetic events for delegate handling. Hosted as a property of the `delegate` method (e.g. `Y.delegate.compileFilter`). @method compileFilter @param selector {String} the selector string to base the filtration on @return {Function} @since 3.2.0 @static **/ delegate.compileFilter = Y.cached(function (selector) { return function (target, e) { return selectorTest(target._node, selector, (e.currentTarget === e.target) ? null : e.currentTarget._node); }; }); /** Regex to test for disabled elements during filtering. This is only relevant to IE to normalize behavior with other browsers, which swallow events that occur to disabled elements. IE fires the event from the parent element instead of the original target, though it does preserve `event.srcElement` as the disabled element. IE also supports disabled on `<a>`, but the event still bubbles, so it acts more like `e.preventDefault()` plus styling. That issue is not handled here because other browsers fire the event on the `<a>`, so delegate is supported in both cases. @property _disabledRE @type {RegExp} @protected @since 3.8.1 **/ delegate._disabledRE = /^(?:button|input|select|textarea)$/i; /** Walks up the parent axis of an event's target, and tests each element against a supplied filter function. If any Nodes, including the container, satisfy the filter, the delegated callback will be triggered for each. Hosted as a protected property of the `delegate` method (e.g. `Y.delegate._applyFilter`). @method _applyFilter @param filter {Function} boolean function to test for inclusion in event notification @param args {Array} the arguments that would be passed to subscribers @param ce {CustomEvent} the DOM event wrapper @return {Node|Node[]|undefined} The Node or Nodes that satisfy the filter @protected **/ delegate._applyFilter = function (filter, args, ce) { var e = args[0], container = ce.el, // facadeless events in IE, have no e.currentTarget target = e.target || e.srcElement, match = [], isContainer = false; // Resolve text nodes to their containing element if (target.nodeType === 3) { target = target.parentNode; } // For IE. IE propagates events from the parent element of disabled // elements, where other browsers swallow the event entirely. To normalize // this in IE, filtering for matching elements should abort if the target // is a disabled form control. if (target.disabled && delegate._disabledRE.test(target.nodeName)) { return match; } // passing target as the first arg rather than leaving well enough alone // making 'this' in the filter function refer to the target. This is to // support bound filter functions. args.unshift(target); if (isString(filter)) { while (target) { isContainer = (target === container); if (selectorTest(target, filter, (isContainer ? null: container))) { match.push(target); } if (isContainer) { break; } target = target.parentNode; } } else { // filter functions are implementer code and should receive wrappers args[0] = Y.one(target); args[1] = new Y.DOMEventFacade(e, container, ce); while (target) { // filter(target, e, extra args...) - this === target if (filter.apply(args[0], args)) { match.push(target); } if (target === container) { break; } target = target.parentNode; args[0] = Y.one(target); } args[1] = e; // restore the raw DOM event } if (match.length <= 1) { match = match[0]; // single match or undefined } // remove the target args.shift(); return match; }; /** * Sets up event delegation on a container element. The delegated event * will use a supplied filter to test if the callback should be executed. * This filter can be either a selector string or a function that returns * a Node to use as the currentTarget for the event. * * The event object for the delegated event is supplied to the callback * function. It is modified slightly in order to support all properties * that may be needed for event delegation. 'currentTarget' is set to * the element that matched the selector string filter or the Node returned * from the filter function. 'container' is set to the element that the * listener is delegated from (this normally would be the 'currentTarget'). * * Filter functions will be called with the arguments that would be passed to * the callback function, including the event object as the first parameter. * The function should return false (or a falsey value) if the success criteria * aren't met, and the Node to use as the event's currentTarget and 'this' * object if they are. * * @method delegate * @param type {string} the event type to delegate * @param fn {function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param el {string|node} the element that is the delegation container * @param filter {string|function} a selector that must match the target of the * event or a function that returns a Node or false. * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.delegate = Y.Event.delegate = delegate; }, '@VERSION@', {"requires": ["node-base"]}); YUI.add('node-event-delegate', function (Y, NAME) { /** * Functionality to make the node a delegated event container * @module node * @submodule node-event-delegate */ /** * <p>Sets up a delegation listener for an event occurring inside the Node. * The delegated event will be verified against a supplied selector or * filtering function to test if the event references at least one node that * should trigger the subscription callback.</p> * * <p>Selector string filters will trigger the callback if the event originated * from a node that matches it or is contained in a node that matches it. * Function filters are called for each Node up the parent axis to the * subscribing container node, and receive at each level the Node and the event * object. The function should return true (or a truthy value) if that Node * should trigger the subscription callback. Note, it is possible for filters * to match multiple Nodes for a single event. In this case, the delegate * callback will be executed for each matching Node.</p> * * <p>For each matching Node, the callback will be executed with its 'this' * object set to the Node matched by the filter (unless a specific context was * provided during subscription), and the provided event's * <code>currentTarget</code> will also be set to the matching Node. The * containing Node from which the subscription was originally made can be * referenced as <code>e.container</code>. * * @method delegate * @param type {String} the event type to delegate * @param fn {Function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param spec {String|Function} a selector that must match the target of the * event or a function to test target and its parents for a match * @param context {Object} optional argument that specifies what 'this' refers to. * @param args* {any} 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for Node */ Y.Node.prototype.delegate = function(type) { var args = Y.Array(arguments, 0, true), index = (Y.Lang.isObject(type) && !Y.Lang.isArray(type)) ? 1 : 2; args.splice(index, 0, this._node); return Y.delegate.apply(Y, args); }; }, '@VERSION@', {"requires": ["node-base", "event-delegate"]}); YUI.add('node-pluginhost', function (Y, NAME) { /** * @module node * @submodule node-pluginhost */ /** * Registers plugins to be instantiated at the class level (plugins * which should be plugged into every instance of Node by default). * * @method plug * @static * @for Node * @param {Function | Array} plugin Either the plugin class, an array of plugin classes or an array of objects (with fn and cfg properties defined) * @param {Object} config (Optional) If plugin is the plugin class, the configuration for the plugin */ Y.Node.plug = function() { var args = Y.Array(arguments); args.unshift(Y.Node); Y.Plugin.Host.plug.apply(Y.Base, args); return Y.Node; }; /** * Unregisters any class level plugins which have been registered by the Node * * @method unplug * @static * * @param {Function | Array} plugin The plugin class, or an array of plugin classes */ Y.Node.unplug = function() { var args = Y.Array(arguments); args.unshift(Y.Node); Y.Plugin.Host.unplug.apply(Y.Base, args); return Y.Node; }; Y.mix(Y.Node, Y.Plugin.Host, false, null, 1); // allow batching of plug/unplug via NodeList // doesn't use NodeList.importMethod because we need real Nodes (not tmpNode) /** * Adds a plugin to each node in the NodeList. * This will instantiate the plugin and attach it to the configured namespace on each node * @method plug * @for NodeList * @param P {Function | Object |Array} Accepts the plugin class, or an * object with a "fn" property specifying the plugin class and * a "cfg" property specifying the configuration for the Plugin. * <p> * Additionally an Array can also be passed in, with the above function or * object values, allowing the user to add multiple plugins in a single call. * </p> * @param config (Optional) If the first argument is the plugin class, the second argument * can be the configuration for the plugin. * @chainable */ Y.NodeList.prototype.plug = function() { var args = arguments; Y.NodeList.each(this, function(node) { Y.Node.prototype.plug.apply(Y.one(node), args); }); return this; }; /** * Removes a plugin from all nodes in the NodeList. This will destroy the * plugin instance and delete the namespace each node. * @method unplug * @for NodeList * @param {String | Function} plugin The namespace of the plugin, or the plugin class with the static NS namespace property defined. If not provided, * all registered plugins are unplugged. * @chainable */ Y.NodeList.prototype.unplug = function() { var args = arguments; Y.NodeList.each(this, function(node) { Y.Node.prototype.unplug.apply(Y.one(node), args); }); return this; }; }, '@VERSION@', {"requires": ["node-base", "pluginhost"]}); YUI.add('node-screen', function (Y, NAME) { /** * Extended Node interface for managing regions and screen positioning. * Adds support for positioning elements and normalizes window size and scroll detection. * @module node * @submodule node-screen */ // these are all "safe" returns, no wrapping required Y.each([ /** * Returns the inner width of the viewport (exludes scrollbar). * @config winWidth * @for Node * @type {Int} */ 'winWidth', /** * Returns the inner height of the viewport (exludes scrollbar). * @config winHeight * @type {Int} */ 'winHeight', /** * Document width * @config docWidth * @type {Int} */ 'docWidth', /** * Document height * @config docHeight * @type {Int} */ 'docHeight', /** * Pixel distance the page has been scrolled horizontally * @config docScrollX * @type {Int} */ 'docScrollX', /** * Pixel distance the page has been scrolled vertically * @config docScrollY * @type {Int} */ 'docScrollY' ], function(name) { Y.Node.ATTRS[name] = { getter: function() { var args = Array.prototype.slice.call(arguments); args.unshift(Y.Node.getDOMNode(this)); return Y.DOM[name].apply(this, args); } }; } ); Y.Node.ATTRS.scrollLeft = { getter: function() { var node = Y.Node.getDOMNode(this); return ('scrollLeft' in node) ? node.scrollLeft : Y.DOM.docScrollX(node); }, setter: function(val) { var node = Y.Node.getDOMNode(this); if (node) { if ('scrollLeft' in node) { node.scrollLeft = val; } else if (node.document || node.nodeType === 9) { Y.DOM._getWin(node).scrollTo(val, Y.DOM.docScrollY(node)); // scroll window if win or doc } } else { } } }; Y.Node.ATTRS.scrollTop = { getter: function() { var node = Y.Node.getDOMNode(this); return ('scrollTop' in node) ? node.scrollTop : Y.DOM.docScrollY(node); }, setter: function(val) { var node = Y.Node.getDOMNode(this); if (node) { if ('scrollTop' in node) { node.scrollTop = val; } else if (node.document || node.nodeType === 9) { Y.DOM._getWin(node).scrollTo(Y.DOM.docScrollX(node), val); // scroll window if win or doc } } else { } } }; Y.Node.importMethod(Y.DOM, [ /** * Gets the current position of the node in page coordinates. * @method getXY * @for Node * @return {Array} The XY position of the node */ 'getXY', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setXY * @param {Array} xy Contains X & Y values for new position (coordinates are page-based) * @chainable */ 'setXY', /** * Gets the current position of the node in page coordinates. * @method getX * @return {Int} The X position of the node */ 'getX', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setX * @param {Int} x X value for new position (coordinates are page-based) * @chainable */ 'setX', /** * Gets the current position of the node in page coordinates. * @method getY * @return {Int} The Y position of the node */ 'getY', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setY * @param {Int} y Y value for new position (coordinates are page-based) * @chainable */ 'setY', /** * Swaps the XY position of this node with another node. * @method swapXY * @param {Node | HTMLElement} otherNode The node to swap with. * @chainable */ 'swapXY' ]); /** * @module node * @submodule node-screen */ /** * Returns a region object for the node * @config region * @for Node * @type Node */ Y.Node.ATTRS.region = { getter: function() { var node = this.getDOMNode(), region; if (node && !node.tagName) { if (node.nodeType === 9) { // document node = node.documentElement; } } if (Y.DOM.isWindow(node)) { region = Y.DOM.viewportRegion(node); } else { region = Y.DOM.region(node); } return region; } }; /** * Returns a region object for the node's viewport * @config viewportRegion * @type Node */ Y.Node.ATTRS.viewportRegion = { getter: function() { return Y.DOM.viewportRegion(Y.Node.getDOMNode(this)); } }; Y.Node.importMethod(Y.DOM, 'inViewportRegion'); // these need special treatment to extract 2nd node arg /** * Compares the intersection of the node with another node or region * @method intersect * @for Node * @param {Node|Object} node2 The node or region to compare with. * @param {Object} altRegion An alternate region to use (rather than this node's). * @return {Object} An object representing the intersection of the regions. */ Y.Node.prototype.intersect = function(node2, altRegion) { var node1 = Y.Node.getDOMNode(this); if (Y.instanceOf(node2, Y.Node)) { // might be a region object node2 = Y.Node.getDOMNode(node2); } return Y.DOM.intersect(node1, node2, altRegion); }; /** * Determines whether or not the node is within the giving region. * @method inRegion * @param {Node|Object} node2 The node or region to compare with. * @param {Boolean} all Whether or not all of the node must be in the region. * @param {Object} altRegion An alternate region to use (rather than this node's). * @return {Boolean} True if in region, false if not. */ Y.Node.prototype.inRegion = function(node2, all, altRegion) { var node1 = Y.Node.getDOMNode(this); if (Y.instanceOf(node2, Y.Node)) { // might be a region object node2 = Y.Node.getDOMNode(node2); } return Y.DOM.inRegion(node1, node2, all, altRegion); }; }, '@VERSION@', {"requires": ["dom-screen", "node-base"]}); YUI.add('node-style', function (Y, NAME) { (function(Y) { /** * Extended Node interface for managing node styles. * @module node * @submodule node-style */ Y.mix(Y.Node.prototype, { /** * Sets a style property of the node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyle * @param {String} attr The style attribute to set. * @param {String|Number} val The value. * @chainable */ setStyle: function(attr, val) { Y.DOM.setStyle(this._node, attr, val); return this; }, /** * Sets multiple style properties on the node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyles * @param {Object} hash An object literal of property:value pairs. * @chainable */ setStyles: function(hash) { Y.DOM.setStyles(this._node, hash); return this; }, /** * Returns the style's current value. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getStyle * @for Node * @param {String} attr The style attribute to retrieve. * @return {String} The current value of the style property for the element. */ getStyle: function(attr) { return Y.DOM.getStyle(this._node, attr); }, /** * Returns the computed value for the given style property. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getComputedStyle * @param {String} attr The style attribute to retrieve. * @return {String} The computed value of the style property for the element. */ getComputedStyle: function(attr) { return Y.DOM.getComputedStyle(this._node, attr); } }); /** * Returns an array of values for each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getStyle * @for NodeList * @see Node.getStyle * @param {String} attr The style attribute to retrieve. * @return {Array} The current values of the style property for the element. */ /** * Returns an array of the computed value for each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getComputedStyle * @see Node.getComputedStyle * @param {String} attr The style attribute to retrieve. * @return {Array} The computed values for each node. */ /** * Sets a style property on each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyle * @see Node.setStyle * @param {String} attr The style attribute to set. * @param {String|Number} val The value. * @chainable */ /** * Sets multiple style properties on each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyles * @see Node.setStyles * @param {Object} hash An object literal of property:value pairs. * @chainable */ // These are broken out to handle undefined return (avoid false positive for // chainable) Y.NodeList.importMethod(Y.Node.prototype, ['getStyle', 'getComputedStyle', 'setStyle', 'setStyles']); })(Y); }, '@VERSION@', {"requires": ["dom-style", "node-base"]}); YUI.add('querystring-stringify-simple', function (Y, NAME) { /*global Y */ /** * <p>Provides Y.QueryString.stringify method for converting objects to Query Strings. * This is a subset implementation of the full querystring-stringify.</p> * <p>This module provides the bare minimum functionality (encoding a hash of simple values), * without the additional support for nested data structures. Every key-value pair is * encoded by encodeURIComponent.</p> * <p>This module provides a minimalistic way for io to handle single-level objects * as transaction data.</p> * * @module querystring * @submodule querystring-stringify-simple */ var QueryString = Y.namespace("QueryString"), EUC = encodeURIComponent; QueryString.stringify = function (obj, c) { var qs = [], // Default behavior is false; standard key notation. s = c && c.arrayKey ? true : false, key, i, l; for (key in obj) { if (obj.hasOwnProperty(key)) { if (Y.Lang.isArray(obj[key])) { for (i = 0, l = obj[key].length; i < l; i++) { qs.push(EUC(s ? key + '[]' : key) + '=' + EUC(obj[key][i])); } } else { qs.push(EUC(key) + '=' + EUC(obj[key])); } } } return qs.join('&'); }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('io-base', function (Y, NAME) { /** Base IO functionality. Provides basic XHR transport support. @module io @submodule io-base @for IO **/ var // List of events that comprise the IO event lifecycle. EVENTS = ['start', 'complete', 'end', 'success', 'failure', 'progress'], // Whitelist of used XHR response object properties. XHR_PROPS = ['status', 'statusText', 'responseText', 'responseXML'], win = Y.config.win, uid = 0; /** The IO class is a utility that brokers HTTP requests through a simplified interface. Specifically, it allows JavaScript to make HTTP requests to a resource without a page reload. The underlying transport for making same-domain requests is the XMLHttpRequest object. IO can also use Flash, if specified as a transport, for cross-domain requests. @class IO @constructor @param {Object} config Object of EventTarget's publish method configurations used to configure IO's events. **/ function IO (config) { var io = this; io._uid = 'io:' + uid++; io._init(config); Y.io._map[io._uid] = io; } IO.prototype = { //-------------------------------------- // Properties //-------------------------------------- /** * A counter that increments for each transaction. * * @property _id * @private * @type {Number} */ _id: 0, /** * Object of IO HTTP headers sent with each transaction. * * @property _headers * @private * @type {Object} */ _headers: { 'X-Requested-With' : 'XMLHttpRequest' }, /** * Object that stores timeout values for any transaction with a defined * "timeout" configuration property. * * @property _timeout * @private * @type {Object} */ _timeout: {}, //-------------------------------------- // Methods //-------------------------------------- _init: function(config) { var io = this, i, len; io.cfg = config || {}; Y.augment(io, Y.EventTarget); for (i = 0, len = EVENTS.length; i < len; ++i) { // Publish IO global events with configurations, if any. // IO global events are set to broadcast by default. // These events use the "io:" namespace. io.publish('io:' + EVENTS[i], Y.merge({ broadcast: 1 }, config)); // Publish IO transaction events with configurations, if // any. These events use the "io-trn:" namespace. io.publish('io-trn:' + EVENTS[i], config); } }, /** * Method that creates a unique transaction object for each request. * * @method _create * @private * @param {Object} cfg Configuration object subset to determine if * the transaction is an XDR or file upload, * requiring an alternate transport. * @param {Number} id Transaction id * @return {Object} The transaction object */ _create: function(config, id) { var io = this, transaction = { id : Y.Lang.isNumber(id) ? id : io._id++, uid: io._uid }, alt = config.xdr ? config.xdr.use : null, form = config.form && config.form.upload ? 'iframe' : null, use; if (alt === 'native') { // Non-IE and IE >= 10 can use XHR level 2 and not rely on an // external transport. alt = Y.UA.ie && !SUPPORTS_CORS ? 'xdr' : null; // Prevent "pre-flight" OPTIONS request by removing the // `X-Requested-With` HTTP header from CORS requests. This header // can be added back on a per-request basis, if desired. io.setHeader('X-Requested-With'); } use = alt || form; transaction = use ? Y.merge(Y.IO.customTransport(use), transaction) : Y.merge(Y.IO.defaultTransport(), transaction); if (transaction.notify) { config.notify = function (e, t, c) { io.notify(e, t, c); }; } if (!use) { if (win && win.FormData && config.data instanceof win.FormData) { transaction.c.upload.onprogress = function (e) { io.progress(transaction, e, config); }; transaction.c.onload = function (e) { io.load(transaction, e, config); }; transaction.c.onerror = function (e) { io.error(transaction, e, config); }; transaction.upload = true; } } return transaction; }, _destroy: function(transaction) { if (win && !transaction.notify && !transaction.xdr) { if (XHR && !transaction.upload) { transaction.c.onreadystatechange = null; } else if (transaction.upload) { transaction.c.upload.onprogress = null; transaction.c.onload = null; transaction.c.onerror = null; } else if (Y.UA.ie && !transaction.e) { // IE, when using XMLHttpRequest as an ActiveX Object, will throw // a "Type Mismatch" error if the event handler is set to "null". transaction.c.abort(); } } transaction = transaction.c = null; }, /** * Method for creating and firing events. * * @method _evt * @private * @param {String} eventName Event to be published. * @param {Object} transaction Transaction object. * @param {Object} config Configuration data subset for event subscription. */ _evt: function(eventName, transaction, config) { var io = this, params, args = config['arguments'], emitFacade = io.cfg.emitFacade, globalEvent = "io:" + eventName, trnEvent = "io-trn:" + eventName; // Workaround for #2532107 this.detach(trnEvent); if (transaction.e) { transaction.c = { status: 0, statusText: transaction.e }; } // Fire event with parameters or an Event Facade. params = [ emitFacade ? { id: transaction.id, data: transaction.c, cfg: config, 'arguments': args } : transaction.id ]; if (!emitFacade) { if (eventName === EVENTS[0] || eventName === EVENTS[2]) { if (args) { params.push(args); } } else { if (transaction.evt) { params.push(transaction.evt); } else { params.push(transaction.c); } if (args) { params.push(args); } } } params.unshift(globalEvent); // Fire global events. io.fire.apply(io, params); // Fire transaction events, if receivers are defined. if (config.on) { params[0] = trnEvent; io.once(trnEvent, config.on[eventName], config.context || Y); io.fire.apply(io, params); } }, /** * Fires event "io:start" and creates, fires a transaction-specific * start event, if `config.on.start` is defined. * * @method start * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ start: function(transaction, config) { /** * Signals the start of an IO request. * @event io:start */ this._evt(EVENTS[0], transaction, config); }, /** * Fires event "io:complete" and creates, fires a * transaction-specific "complete" event, if config.on.complete is * defined. * * @method complete * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ complete: function(transaction, config) { /** * Signals the completion of the request-response phase of a * transaction. Response status and data are accessible, if * available, in this event. * @event io:complete */ this._evt(EVENTS[1], transaction, config); }, /** * Fires event "io:end" and creates, fires a transaction-specific "end" * event, if config.on.end is defined. * * @method end * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ end: function(transaction, config) { /** * Signals the end of the transaction lifecycle. * @event io:end */ this._evt(EVENTS[2], transaction, config); this._destroy(transaction); }, /** * Fires event "io:success" and creates, fires a transaction-specific * "success" event, if config.on.success is defined. * * @method success * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ success: function(transaction, config) { /** * Signals an HTTP response with status in the 2xx range. * Fires after io:complete. * @event io:success */ this._evt(EVENTS[3], transaction, config); this.end(transaction, config); }, /** * Fires event "io:failure" and creates, fires a transaction-specific * "failure" event, if config.on.failure is defined. * * @method failure * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ failure: function(transaction, config) { /** * Signals an HTTP response with status outside of the 2xx range. * Fires after io:complete. * @event io:failure */ this._evt(EVENTS[4], transaction, config); this.end(transaction, config); }, /** * Fires event "io:progress" and creates, fires a transaction-specific * "progress" event -- for XMLHttpRequest file upload -- if * config.on.progress is defined. * * @method progress * @param {Object} transaction Transaction object. * @param {Object} progress event. * @param {Object} config Configuration object for the transaction. */ progress: function(transaction, e, config) { /** * Signals the interactive state during a file upload transaction. * This event fires after io:start and before io:complete. * @event io:progress */ transaction.evt = e; this._evt(EVENTS[5], transaction, config); }, /** * Fires event "io:complete" and creates, fires a transaction-specific * "complete" event -- for XMLHttpRequest file upload -- if * config.on.complete is defined. * * @method load * @param {Object} transaction Transaction object. * @param {Object} load event. * @param {Object} config Configuration object for the transaction. */ load: function (transaction, e, config) { transaction.evt = e.target; this._evt(EVENTS[1], transaction, config); }, /** * Fires event "io:failure" and creates, fires a transaction-specific * "failure" event -- for XMLHttpRequest file upload -- if * config.on.failure is defined. * * @method error * @param {Object} transaction Transaction object. * @param {Object} error event. * @param {Object} config Configuration object for the transaction. */ error: function (transaction, e, config) { transaction.evt = e; this._evt(EVENTS[4], transaction, config); }, /** * Retry an XDR transaction, using the Flash tranport, if the native * transport fails. * * @method _retry * @private * @param {Object} transaction Transaction object. * @param {String} uri Qualified path to transaction resource. * @param {Object} config Configuration object for the transaction. */ _retry: function(transaction, uri, config) { this._destroy(transaction); config.xdr.use = 'flash'; return this.send(uri, config, transaction.id); }, /** * Method that concatenates string data for HTTP GET transactions. * * @method _concat * @private * @param {String} uri URI or root data. * @param {String} data Data to be concatenated onto URI. * @return {String} */ _concat: function(uri, data) { uri += (uri.indexOf('?') === -1 ? '?' : '&') + data; return uri; }, /** * Stores default client headers for all transactions. If a label is * passed with no value argument, the header will be deleted. * * @method setHeader * @param {String} name HTTP header * @param {String} value HTTP header value */ setHeader: function(name, value) { if (value) { this._headers[name] = value; } else { delete this._headers[name]; } }, /** * Method that sets all HTTP headers to be sent in a transaction. * * @method _setHeaders * @private * @param {Object} transaction - XHR instance for the specific transaction. * @param {Object} headers - HTTP headers for the specific transaction, as * defined in the configuration object passed to YUI.io(). */ _setHeaders: function(transaction, headers) { headers = Y.merge(this._headers, headers); Y.Object.each(headers, function(value, name) { if (value !== 'disable') { transaction.setRequestHeader(name, headers[name]); } }); }, /** * Starts timeout count if the configuration object has a defined * timeout property. * * @method _startTimeout * @private * @param {Object} transaction Transaction object generated by _create(). * @param {Object} timeout Timeout in milliseconds. */ _startTimeout: function(transaction, timeout) { var io = this; io._timeout[transaction.id] = setTimeout(function() { io._abort(transaction, 'timeout'); }, timeout); }, /** * Clears the timeout interval started by _startTimeout(). * * @method _clearTimeout * @private * @param {Number} id - Transaction id. */ _clearTimeout: function(id) { clearTimeout(this._timeout[id]); delete this._timeout[id]; }, /** * Method that determines if a transaction response qualifies as success * or failure, based on the response HTTP status code, and fires the * appropriate success or failure events. * * @method _result * @private * @static * @param {Object} transaction Transaction object generated by _create(). * @param {Object} config Configuration object passed to io(). */ _result: function(transaction, config) { var status; // Firefox will throw an exception if attempting to access // an XHR object's status property, after a request is aborted. try { status = transaction.c.status; } catch(e) { status = 0; } // IE reports HTTP 204 as HTTP 1223. if (status >= 200 && status < 300 || status === 304 || status === 1223) { this.success(transaction, config); } else { this.failure(transaction, config); } }, /** * Event handler bound to onreadystatechange. * * @method _rS * @private * @param {Object} transaction Transaction object generated by _create(). * @param {Object} config Configuration object passed to YUI.io(). */ _rS: function(transaction, config) { var io = this; if (transaction.c.readyState === 4) { if (config.timeout) { io._clearTimeout(transaction.id); } // Yield in the event of request timeout or abort. setTimeout(function() { io.complete(transaction, config); io._result(transaction, config); }, 0); } }, /** * Terminates a transaction due to an explicit abort or timeout. * * @method _abort * @private * @param {Object} transaction Transaction object generated by _create(). * @param {String} type Identifies timed out or aborted transaction. */ _abort: function(transaction, type) { if (transaction && transaction.c) { transaction.e = type; transaction.c.abort(); } }, /** * Requests a transaction. `send()` is implemented as `Y.io()`. Each * transaction may include a configuration object. Its properties are: * * <dl> * <dt>method</dt> * <dd>HTTP method verb (e.g., GET or POST). If this property is not * not defined, the default value will be GET.</dd> * * <dt>data</dt> * <dd>This is the name-value string that will be sent as the * transaction data. If the request is HTTP GET, the data become * part of querystring. If HTTP POST, the data are sent in the * message body.</dd> * * <dt>xdr</dt> * <dd>Defines the transport to be used for cross-domain requests. * By setting this property, the transaction will use the specified * transport instead of XMLHttpRequest. The properties of the * transport object are: * <dl> * <dt>use</dt> * <dd>The transport to be used: 'flash' or 'native'</dd> * <dt>dataType</dt> * <dd>Set the value to 'XML' if that is the expected response * content type.</dd> * <dt>credentials</dt> * <dd>Set the value to 'true' to set XHR.withCredentials property to true.</dd> * </dl></dd> * * <dt>form</dt> * <dd>Form serialization configuration object. Its properties are: * <dl> * <dt>id</dt> * <dd>Node object or id of HTML form</dd> * <dt>useDisabled</dt> * <dd>`true` to also serialize disabled form field values * (defaults to `false`)</dd> * </dl></dd> * * <dt>on</dt> * <dd>Assigns transaction event subscriptions. Available events are: * <dl> * <dt>start</dt> * <dd>Fires when a request is sent to a resource.</dd> * <dt>complete</dt> * <dd>Fires when the transaction is complete.</dd> * <dt>success</dt> * <dd>Fires when the HTTP response status is within the 2xx * range.</dd> * <dt>failure</dt> * <dd>Fires when the HTTP response status is outside the 2xx * range, if an exception occurs, if the transation is aborted, * or if the transaction exceeds a configured `timeout`.</dd> * <dt>end</dt> * <dd>Fires at the conclusion of the transaction * lifecycle, after `success` or `failure`.</dd> * </dl> * * <p>Callback functions for `start` and `end` receive the id of the * transaction as a first argument. For `complete`, `success`, and * `failure`, callbacks receive the id and the response object * (usually the XMLHttpRequest instance). If the `arguments` * property was included in the configuration object passed to * `Y.io()`, the configured data will be passed to all callbacks as * the last argument.</p> * </dd> * * <dt>sync</dt> * <dd>Pass `true` to make a same-domain transaction synchronous. * <strong>CAVEAT</strong>: This will negatively impact the user * experience. Have a <em>very</em> good reason if you intend to use * this.</dd> * * <dt>context</dt> * <dd>The "`this'" object for all configured event handlers. If a * specific context is needed for individual callbacks, bind the * callback to a context using `Y.bind()`.</dd> * * <dt>headers</dt> * <dd>Object map of transaction headers to send to the server. The * object keys are the header names and the values are the header * values.</dd> * * <dt>timeout</dt> * <dd>Millisecond threshold for the transaction before being * automatically aborted.</dd> * * <dt>arguments</dt> * <dd>User-defined data passed to all registered event handlers. * This value is available as the second argument in the "start" and * "end" event handlers. It is the third argument in the "complete", * "success", and "failure" event handlers. <strong>Be sure to quote * this property name in the transaction configuration as * "arguments" is a reserved word in JavaScript</strong> (e.g. * `Y.io({ ..., "arguments": stuff })`).</dd> * </dl> * * @method send * @public * @param {String} uri Qualified path to transaction resource. * @param {Object} config Configuration object for the transaction. * @param {Number} id Transaction id, if already set. * @return {Object} */ send: function(uri, config, id) { var transaction, method, i, len, sync, data, io = this, u = uri, response = {}; config = config ? Y.Object(config) : {}; transaction = io._create(config, id); method = config.method ? config.method.toUpperCase() : 'GET'; sync = config.sync; data = config.data; // Serialize a map object into a key-value string using // querystring-stringify-simple. if ((Y.Lang.isObject(data) && !data.nodeType) && !transaction.upload) { if (Y.QueryString && Y.QueryString.stringify) { config.data = data = Y.QueryString.stringify(data); } else { } } if (config.form) { if (config.form.upload) { // This is a file upload transaction, calling // upload() in io-upload-iframe. return io.upload(transaction, uri, config); } else { // Serialize HTML form data into a key-value string. data = io._serialize(config.form, data); } } // Convert falsy values to an empty string. This way IE can't be // rediculous and translate `undefined` to "undefined". data || (data = ''); if (data) { switch (method) { case 'GET': case 'HEAD': case 'DELETE': u = io._concat(u, data); data = ''; break; case 'POST': case 'PUT': // If Content-Type is defined in the configuration object, or // or as a default header, it will be used instead of // 'application/x-www-form-urlencoded; charset=UTF-8' config.headers = Y.merge({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, config.headers); break; } } if (transaction.xdr) { // Route data to io-xdr module for flash and XDomainRequest. return io.xdr(u, transaction, config); } else if (transaction.notify) { // Route data to custom transport return transaction.c.send(transaction, uri, config); } if (!sync && !transaction.upload) { transaction.c.onreadystatechange = function() { io._rS(transaction, config); }; } try { // Determine if request is to be set as // synchronous or asynchronous. transaction.c.open(method, u, !sync, config.username || null, config.password || null); io._setHeaders(transaction.c, config.headers || {}); io.start(transaction, config); // Will work only in browsers that implement the // Cross-Origin Resource Sharing draft. if (config.xdr && config.xdr.credentials && SUPPORTS_CORS) { transaction.c.withCredentials = true; } // Using "null" with HTTP POST will result in a request // with no Content-Length header defined. transaction.c.send(data); if (sync) { // Create a response object for synchronous transactions, // mixing id and arguments properties with the xhr // properties whitelist. for (i = 0, len = XHR_PROPS.length; i < len; ++i) { response[XHR_PROPS[i]] = transaction.c[XHR_PROPS[i]]; } response.getAllResponseHeaders = function() { return transaction.c.getAllResponseHeaders(); }; response.getResponseHeader = function(name) { return transaction.c.getResponseHeader(name); }; io.complete(transaction, config); io._result(transaction, config); return response; } } catch(e) { if (transaction.xdr) { // This exception is usually thrown by browsers // that do not support XMLHttpRequest Level 2. // Retry the request with the XDR transport set // to 'flash'. If the Flash transport is not // initialized or available, the transaction // will resolve to a transport error. return io._retry(transaction, uri, config); } else { io.complete(transaction, config); io._result(transaction, config); } } // If config.timeout is defined, and the request is standard XHR, // initialize timeout polling. if (config.timeout) { io._startTimeout(transaction, config.timeout); } return { id: transaction.id, abort: function() { return transaction.c ? io._abort(transaction, 'abort') : false; }, isInProgress: function() { return transaction.c ? (transaction.c.readyState % 4) : false; }, io: io }; } }; /** Method for initiating an ajax call. The first argument is the url end point for the call. The second argument is an object to configure the transaction and attach event subscriptions. The configuration object supports the following properties: <dl> <dt>method</dt> <dd>HTTP method verb (e.g., GET or POST). If this property is not not defined, the default value will be GET.</dd> <dt>data</dt> <dd>This is the name-value string that will be sent as the transaction data. If the request is HTTP GET, the data become part of querystring. If HTTP POST, the data are sent in the message body.</dd> <dt>xdr</dt> <dd>Defines the transport to be used for cross-domain requests. By setting this property, the transaction will use the specified transport instead of XMLHttpRequest. The properties of the transport object are: <dl> <dt>use</dt> <dd>The transport to be used: 'flash' or 'native'</dd> <dt>dataType</dt> <dd>Set the value to 'XML' if that is the expected response content type.</dd> </dl></dd> <dt>form</dt> <dd>Form serialization configuration object. Its properties are: <dl> <dt>id</dt> <dd>Node object or id of HTML form</dd> <dt>useDisabled</dt> <dd>`true` to also serialize disabled form field values (defaults to `false`)</dd> </dl></dd> <dt>on</dt> <dd>Assigns transaction event subscriptions. Available events are: <dl> <dt>start</dt> <dd>Fires when a request is sent to a resource.</dd> <dt>complete</dt> <dd>Fires when the transaction is complete.</dd> <dt>success</dt> <dd>Fires when the HTTP response status is within the 2xx range.</dd> <dt>failure</dt> <dd>Fires when the HTTP response status is outside the 2xx range, if an exception occurs, if the transation is aborted, or if the transaction exceeds a configured `timeout`.</dd> <dt>end</dt> <dd>Fires at the conclusion of the transaction lifecycle, after `success` or `failure`.</dd> </dl> <p>Callback functions for `start` and `end` receive the id of the transaction as a first argument. For `complete`, `success`, and `failure`, callbacks receive the id and the response object (usually the XMLHttpRequest instance). If the `arguments` property was included in the configuration object passed to `Y.io()`, the configured data will be passed to all callbacks as the last argument.</p> </dd> <dt>sync</dt> <dd>Pass `true` to make a same-domain transaction synchronous. <strong>CAVEAT</strong>: This will negatively impact the user experience. Have a <em>very</em> good reason if you intend to use this.</dd> <dt>context</dt> <dd>The "`this'" object for all configured event handlers. If a specific context is needed for individual callbacks, bind the callback to a context using `Y.bind()`.</dd> <dt>headers</dt> <dd>Object map of transaction headers to send to the server. The object keys are the header names and the values are the header values.</dd> <dt>timeout</dt> <dd>Millisecond threshold for the transaction before being automatically aborted.</dd> <dt>arguments</dt> <dd>User-defined data passed to all registered event handlers. This value is available as the second argument in the "start" and "end" event handlers. It is the third argument in the "complete", "success", and "failure" event handlers. <strong>Be sure to quote this property name in the transaction configuration as "arguments" is a reserved word in JavaScript</strong> (e.g. `Y.io({ ..., "arguments": stuff })`).</dd> </dl> @method io @static @param {String} url qualified path to transaction resource. @param {Object} config configuration object for the transaction. @return {Object} @for YUI **/ Y.io = function(url, config) { // Calling IO through the static interface will use and reuse // an instance of IO. var transaction = Y.io._map['io:0'] || new IO(); return transaction.send.apply(transaction, [url, config]); }; /** Method for setting and deleting IO HTTP headers to be sent with every request. Hosted as a property on the `io` function (e.g. `Y.io.header`). @method header @param {String} name HTTP header @param {String} value HTTP header value @static **/ Y.io.header = function(name, value) { // Calling IO through the static interface will use and reuse // an instance of IO. var transaction = Y.io._map['io:0'] || new IO(); transaction.setHeader(name, value); }; Y.IO = IO; // Map of all IO instances created. Y.io._map = {}; var XHR = win && win.XMLHttpRequest, XDR = win && win.XDomainRequest, AX = win && win.ActiveXObject, // Checks for the presence of the `withCredentials` in an XHR instance // object, which will be present if the environment supports CORS. SUPPORTS_CORS = XHR && 'withCredentials' in (new XMLHttpRequest()); Y.mix(Y.IO, { /** * The ID of the default IO transport, defaults to `xhr` * @property _default * @type {String} * @static */ _default: 'xhr', /** * * @method defaultTransport * @static * @param {String} [id] The transport to set as the default, if empty a new transport is created. * @return {Object} The transport object with a `send` method */ defaultTransport: function(id) { if (id) { Y.IO._default = id; } else { var o = { c: Y.IO.transports[Y.IO._default](), notify: Y.IO._default === 'xhr' ? false : true }; return o; } }, /** * An object hash of custom transports available to IO * @property transports * @type {Object} * @static */ transports: { xhr: function () { return XHR ? new XMLHttpRequest() : AX ? new ActiveXObject('Microsoft.XMLHTTP') : null; }, xdr: function () { return XDR ? new XDomainRequest() : null; }, iframe: function () { return {}; }, flash: null, nodejs: null }, /** * Create a custom transport of type and return it's object * @method customTransport * @param {String} id The id of the transport to create. * @static */ customTransport: function(id) { var o = { c: Y.IO.transports[id]() }; o[(id === 'xdr' || id === 'flash') ? 'xdr' : 'notify'] = true; return o; } }); Y.mix(Y.IO.prototype, { /** * Fired from the notify method of the transport which in turn fires * the event on the IO object. * @method notify * @param {String} event The name of the event * @param {Object} transaction The transaction object * @param {Object} config The configuration object for this transaction */ notify: function(event, transaction, config) { var io = this; switch (event) { case 'timeout': case 'abort': case 'transport error': transaction.c = { status: 0, statusText: event }; event = 'failure'; default: io[event].apply(io, [transaction, config]); } } }); }, '@VERSION@', {"requires": ["event-custom-base", "querystring-stringify-simple"]}); YUI.add('json-parse', function (Y, NAME) { var _JSON = Y.config.global.JSON; Y.namespace('JSON').parse = function (obj, reviver, space) { return _JSON.parse((typeof obj === 'string' ? obj : obj + ''), reviver, space); }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('transition', function (Y, NAME) { /** * Provides the transition method for Node. * Transition has no API of its own, but adds the transition method to Node. * * @module transition * @requires node-style */ var CAMEL_VENDOR_PREFIX = '', VENDOR_PREFIX = '', DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', DOCUMENT_STYLE = DOCUMENT[DOCUMENT_ELEMENT].style, TRANSITION_CAMEL = 'transition', TRANSITION_PROPERTY_CAMEL = 'transitionProperty', TRANSITION_PROPERTY, TRANSITION_DURATION, TRANSITION_TIMING_FUNCTION, TRANSITION_DELAY, TRANSITION_END, ON_TRANSITION_END, EMPTY_OBJ = {}, VENDORS = [ 'Webkit', 'Moz' ], VENDOR_TRANSITION_END = { Webkit: 'webkitTransitionEnd' }, /** * A class for constructing transition instances. * Adds the "transition" method to Node. * @class Transition * @constructor */ Transition = function() { this.init.apply(this, arguments); }; // One off handling of transform-prefixing. Transition._TRANSFORM = 'transform'; Transition._toCamel = function(property) { property = property.replace(/-([a-z])/gi, function(m0, m1) { return m1.toUpperCase(); }); return property; }; Transition._toHyphen = function(property) { property = property.replace(/([A-Z]?)([a-z]+)([A-Z]?)/g, function(m0, m1, m2, m3) { var str = ((m1) ? '-' + m1.toLowerCase() : '') + m2; if (m3) { str += '-' + m3.toLowerCase(); } return str; }); return property; }; Transition.SHOW_TRANSITION = 'fadeIn'; Transition.HIDE_TRANSITION = 'fadeOut'; Transition.useNative = false; // Map transition properties to vendor-specific versions. if ('transition' in DOCUMENT_STYLE && 'transitionProperty' in DOCUMENT_STYLE && 'transitionDuration' in DOCUMENT_STYLE && 'transitionTimingFunction' in DOCUMENT_STYLE && 'transitionDelay' in DOCUMENT_STYLE) { Transition.useNative = true; Transition.supported = true; // TODO: remove } else { Y.Array.each(VENDORS, function(val) { // then vendor specific var property = val + 'Transition'; if (property in DOCUMENT[DOCUMENT_ELEMENT].style) { CAMEL_VENDOR_PREFIX = val; VENDOR_PREFIX = Transition._toHyphen(val) + '-'; Transition.useNative = true; Transition.supported = true; // TODO: remove Transition._VENDOR_PREFIX = val; } }); } // Map transform property to vendor-specific versions. // One-off required for cssText injection. if (typeof DOCUMENT_STYLE.transform === 'undefined') { Y.Array.each(VENDORS, function(val) { // then vendor specific var property = val + 'Transform'; if (typeof DOCUMENT_STYLE[property] !== 'undefined') { Transition._TRANSFORM = property; } }); } if (CAMEL_VENDOR_PREFIX) { TRANSITION_CAMEL = CAMEL_VENDOR_PREFIX + 'Transition'; TRANSITION_PROPERTY_CAMEL = CAMEL_VENDOR_PREFIX + 'TransitionProperty'; } TRANSITION_PROPERTY = VENDOR_PREFIX + 'transition-property'; TRANSITION_DURATION = VENDOR_PREFIX + 'transition-duration'; TRANSITION_TIMING_FUNCTION = VENDOR_PREFIX + 'transition-timing-function'; TRANSITION_DELAY = VENDOR_PREFIX + 'transition-delay'; TRANSITION_END = 'transitionend'; ON_TRANSITION_END = 'on' + CAMEL_VENDOR_PREFIX.toLowerCase() + 'transitionend'; TRANSITION_END = VENDOR_TRANSITION_END[CAMEL_VENDOR_PREFIX] || TRANSITION_END; Transition.fx = {}; Transition.toggles = {}; Transition._hasEnd = {}; Transition._reKeywords = /^(?:node|duration|iterations|easing|delay|on|onstart|onend)$/i; Y.Node.DOM_EVENTS[TRANSITION_END] = 1; Transition.NAME = 'transition'; Transition.DEFAULT_EASING = 'ease'; Transition.DEFAULT_DURATION = 0.5; Transition.DEFAULT_DELAY = 0; Transition._nodeAttrs = {}; Transition.prototype = { constructor: Transition, init: function(node, config) { var anim = this; anim._node = node; if (!anim._running && config) { anim._config = config; node._transition = anim; // cache for reuse anim._duration = ('duration' in config) ? config.duration: anim.constructor.DEFAULT_DURATION; anim._delay = ('delay' in config) ? config.delay: anim.constructor.DEFAULT_DELAY; anim._easing = config.easing || anim.constructor.DEFAULT_EASING; anim._count = 0; // track number of animated properties anim._running = false; } return anim; }, addProperty: function(prop, config) { var anim = this, node = this._node, uid = Y.stamp(node), nodeInstance = Y.one(node), attrs = Transition._nodeAttrs[uid], computed, compareVal, dur, attr, val; if (!attrs) { attrs = Transition._nodeAttrs[uid] = {}; } attr = attrs[prop]; // might just be a value if (config && config.value !== undefined) { val = config.value; } else if (config !== undefined) { val = config; config = EMPTY_OBJ; } if (typeof val === 'function') { val = val.call(nodeInstance, nodeInstance); } if (attr && attr.transition) { // take control if another transition owns this property if (attr.transition !== anim) { attr.transition._count--; // remapping attr to this transition } } anim._count++; // properties per transition // make 0 async and fire events dur = ((typeof config.duration !== 'undefined') ? config.duration : anim._duration) || 0.0001; attrs[prop] = { value: val, duration: dur, delay: (typeof config.delay !== 'undefined') ? config.delay : anim._delay, easing: config.easing || anim._easing, transition: anim }; // native end event doesnt fire when setting to same value // supplementing with timer // val may be a string or number (height: 0, etc), but computedStyle is always string computed = Y.DOM.getComputedStyle(node, prop); compareVal = (typeof val === 'string') ? computed : parseFloat(computed); if (Transition.useNative && compareVal === val) { setTimeout(function() { anim._onNativeEnd.call(node, { propertyName: prop, elapsedTime: dur }); }, dur * 1000); } }, removeProperty: function(prop) { var anim = this, attrs = Transition._nodeAttrs[Y.stamp(anim._node)]; if (attrs && attrs[prop]) { delete attrs[prop]; anim._count--; } }, initAttrs: function(config) { var attr, node = this._node; if (config.transform && !config[Transition._TRANSFORM]) { config[Transition._TRANSFORM] = config.transform; delete config.transform; // TODO: copy } for (attr in config) { if (config.hasOwnProperty(attr) && !Transition._reKeywords.test(attr)) { this.addProperty(attr, config[attr]); // when size is auto or % webkit starts from zero instead of computed // (https://bugs.webkit.org/show_bug.cgi?id=16020) // TODO: selective set if (node.style[attr] === '') { Y.DOM.setStyle(node, attr, Y.DOM.getComputedStyle(node, attr)); } } } }, /** * Starts or an animation. * @method run * @chainable * @private */ run: function(callback) { var anim = this, node = anim._node, config = anim._config, data = { type: 'transition:start', config: config }; if (!anim._running) { anim._running = true; if (config.on && config.on.start) { config.on.start.call(Y.one(node), data); } anim.initAttrs(anim._config); anim._callback = callback; anim._start(); } return anim; }, _start: function() { this._runNative(); }, _prepDur: function(dur) { dur = parseFloat(dur) * 1000; return dur + 'ms'; }, _runNative: function() { var anim = this, node = anim._node, uid = Y.stamp(node), style = node.style, computed = node.ownerDocument.defaultView.getComputedStyle(node), attrs = Transition._nodeAttrs[uid], cssText = '', cssTransition = computed[Transition._toCamel(TRANSITION_PROPERTY)], transitionText = TRANSITION_PROPERTY + ': ', duration = TRANSITION_DURATION + ': ', easing = TRANSITION_TIMING_FUNCTION + ': ', delay = TRANSITION_DELAY + ': ', hyphy, attr, name; // preserve existing transitions if (cssTransition !== 'all') { transitionText += cssTransition + ','; duration += computed[Transition._toCamel(TRANSITION_DURATION)] + ','; easing += computed[Transition._toCamel(TRANSITION_TIMING_FUNCTION)] + ','; delay += computed[Transition._toCamel(TRANSITION_DELAY)] + ','; } // run transitions mapped to this instance for (name in attrs) { hyphy = Transition._toHyphen(name); attr = attrs[name]; if ((attr = attrs[name]) && attr.transition === anim) { if (name in node.style) { // only native styles allowed duration += anim._prepDur(attr.duration) + ','; delay += anim._prepDur(attr.delay) + ','; easing += (attr.easing) + ','; transitionText += hyphy + ','; cssText += hyphy + ': ' + attr.value + '; '; } else { this.removeProperty(name); } } } transitionText = transitionText.replace(/,$/, ';'); duration = duration.replace(/,$/, ';'); easing = easing.replace(/,$/, ';'); delay = delay.replace(/,$/, ';'); // only one native end event per node if (!Transition._hasEnd[uid]) { node.addEventListener(TRANSITION_END, anim._onNativeEnd, ''); Transition._hasEnd[uid] = true; } style.cssText += transitionText + duration + easing + delay + cssText; }, _end: function(elapsed) { var anim = this, node = anim._node, callback = anim._callback, config = anim._config, data = { type: 'transition:end', config: config, elapsedTime: elapsed }, nodeInstance = Y.one(node); anim._running = false; anim._callback = null; if (node) { if (config.on && config.on.end) { setTimeout(function() { // IE: allow previous update to finish config.on.end.call(nodeInstance, data); // nested to ensure proper fire order if (callback) { callback.call(nodeInstance, data); } }, 1); } else if (callback) { setTimeout(function() { // IE: allow previous update to finish callback.call(nodeInstance, data); }, 1); } } }, _endNative: function(name) { var node = this._node, value = node.ownerDocument.defaultView.getComputedStyle(node, '')[Transition._toCamel(TRANSITION_PROPERTY)]; name = Transition._toHyphen(name); if (typeof value === 'string') { value = value.replace(new RegExp('(?:^|,\\s)' + name + ',?'), ','); value = value.replace(/^,|,$/, ''); node.style[TRANSITION_CAMEL] = value; } }, _onNativeEnd: function(e) { var node = this, uid = Y.stamp(node), event = e,//e._event, name = Transition._toCamel(event.propertyName), elapsed = event.elapsedTime, attrs = Transition._nodeAttrs[uid], attr = attrs[name], anim = (attr) ? attr.transition : null, data, config; if (anim) { anim.removeProperty(name); anim._endNative(name); config = anim._config[name]; data = { type: 'propertyEnd', propertyName: name, elapsedTime: elapsed, config: config }; if (config && config.on && config.on.end) { config.on.end.call(Y.one(node), data); } if (anim._count <= 0) { // after propertyEnd fires anim._end(elapsed); node.style[TRANSITION_PROPERTY_CAMEL] = ''; // clean up style } } }, destroy: function() { var anim = this, node = anim._node; if (node) { node.removeEventListener(TRANSITION_END, anim._onNativeEnd, false); anim._node = null; } } }; Y.Transition = Transition; Y.TransitionNative = Transition; // TODO: remove /** * Animate one or more css properties to a given value. Requires the "transition" module. * <pre>example usage: * Y.one('#demo').transition({ * duration: 1, // in seconds, default is 0.5 * easing: 'ease-out', // default is 'ease' * delay: '1', // delay start for 1 second, default is 0 * * height: '10px', * width: '10px', * * opacity: { // per property * value: 0, * duration: 2, * delay: 2, * easing: 'ease-in' * } * }); * </pre> * @for Node * @method transition * @param {Object} config An object containing one or more style properties, a duration and an easing. * @param {Function} callback A function to run after the transition has completed. * @chainable */ Y.Node.prototype.transition = function(name, config, callback) { var transitionAttrs = Transition._nodeAttrs[Y.stamp(this._node)], anim = (transitionAttrs) ? transitionAttrs.transition || null : null, fxConfig, prop; if (typeof name === 'string') { // named effect, pull config from registry if (typeof config === 'function') { callback = config; config = null; } fxConfig = Transition.fx[name]; if (config && typeof config !== 'boolean') { config = Y.clone(config); for (prop in fxConfig) { if (fxConfig.hasOwnProperty(prop)) { if (! (prop in config)) { config[prop] = fxConfig[prop]; } } } } else { config = fxConfig; } } else { // name is a config, config is a callback or undefined callback = config; config = name; } if (anim && !anim._running) { anim.init(this, config); } else { anim = new Transition(this._node, config); } anim.run(callback); return this; }; Y.Node.prototype.show = function(name, config, callback) { this._show(); // show prior to transition if (name && Y.Transition) { if (typeof name !== 'string' && !name.push) { // named effect or array of effects supercedes default if (typeof config === 'function') { callback = config; config = name; } name = Transition.SHOW_TRANSITION; } this.transition(name, config, callback); } return this; }; Y.NodeList.prototype.show = function(name, config, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { Y.one(node).show(name, config, callback); } return this; }; var _wrapCallBack = function(anim, fn, callback) { return function() { if (fn) { fn.call(anim); } if (callback && typeof callback === 'function') { callback.apply(anim._node, arguments); } }; }; Y.Node.prototype.hide = function(name, config, callback) { if (name && Y.Transition) { if (typeof config === 'function') { callback = config; config = null; } callback = _wrapCallBack(this, this._hide, callback); // wrap with existing callback if (typeof name !== 'string' && !name.push) { // named effect or array of effects supercedes default if (typeof config === 'function') { callback = config; config = name; } name = Transition.HIDE_TRANSITION; } this.transition(name, config, callback); } else { this._hide(); } return this; }; Y.NodeList.prototype.hide = function(name, config, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { Y.one(node).hide(name, config, callback); } return this; }; /** * Animate one or more css properties to a given value. Requires the "transition" module. * <pre>example usage: * Y.all('.demo').transition({ * duration: 1, // in seconds, default is 0.5 * easing: 'ease-out', // default is 'ease' * delay: '1', // delay start for 1 second, default is 0 * * height: '10px', * width: '10px', * * opacity: { // per property * value: 0, * duration: 2, * delay: 2, * easing: 'ease-in' * } * }); * </pre> * @for NodeList * @method transition * @param {Object} config An object containing one or more style properties, a duration and an easing. * @param {Function} callback A function to run after the transition has completed. The callback fires * once per item in the NodeList. * @chainable */ Y.NodeList.prototype.transition = function(config, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { Y.one(node).transition(config, callback); } return this; }; Y.Node.prototype.toggleView = function(name, on, callback) { this._toggles = this._toggles || []; callback = arguments[arguments.length - 1]; if (typeof name !== 'string') { // no transition, just toggle on = name; this._toggleView(on, callback); // call original _toggleView in Y.Node return; } if (typeof on === 'function') { // Ignore "on" if used for callback argument. on = undefined; } if (typeof on === 'undefined' && name in this._toggles) { // reverse current toggle on = ! this._toggles[name]; } on = (on) ? 1 : 0; if (on) { this._show(); } else { callback = _wrapCallBack(this, this._hide, callback); } this._toggles[name] = on; this.transition(Y.Transition.toggles[name][on], callback); return this; }; Y.NodeList.prototype.toggleView = function(name, on, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { node = Y.one(node); node.toggleView.apply(node, arguments); } return this; }; Y.mix(Transition.fx, { fadeOut: { opacity: 0, duration: 0.5, easing: 'ease-out' }, fadeIn: { opacity: 1, duration: 0.5, easing: 'ease-in' }, sizeOut: { height: 0, width: 0, duration: 0.75, easing: 'ease-out' }, sizeIn: { height: function(node) { return node.get('scrollHeight') + 'px'; }, width: function(node) { return node.get('scrollWidth') + 'px'; }, duration: 0.5, easing: 'ease-in', on: { start: function() { var overflow = this.getStyle('overflow'); if (overflow !== 'hidden') { // enable scrollHeight/Width this.setStyle('overflow', 'hidden'); this._transitionOverflow = overflow; } }, end: function() { if (this._transitionOverflow) { // revert overridden value this.setStyle('overflow', this._transitionOverflow); delete this._transitionOverflow; } } } } }); Y.mix(Transition.toggles, { size: ['sizeOut', 'sizeIn'], fade: ['fadeOut', 'fadeIn'] }); }, '@VERSION@', {"requires": ["node-style"]}); YUI.add('selector-css2', function (Y, NAME) { /** * The selector module provides helper methods allowing CSS2 Selectors to be used with DOM elements. * @module dom * @submodule selector-css2 * @for Selector */ /* * Provides helper methods for collecting and filtering DOM elements. */ var PARENT_NODE = 'parentNode', TAG_NAME = 'tagName', ATTRIBUTES = 'attributes', COMBINATOR = 'combinator', PSEUDOS = 'pseudos', Selector = Y.Selector, SelectorCSS2 = { _reRegExpTokens: /([\^\$\?\[\]\*\+\-\.\(\)\|\\])/, SORT_RESULTS: true, // TODO: better detection, document specific _isXML: (function() { var isXML = (Y.config.doc.createElement('div').tagName !== 'DIV'); return isXML; }()), /** * Mapping of shorthand tokens to corresponding attribute selector * @property shorthand * @type object */ shorthand: { '\\#(-?[_a-z0-9]+[-\\w\\uE000]*)': '[id=$1]', '\\.(-?[_a-z]+[-\\w\\uE000]*)': '[className~=$1]' }, /** * List of operators and corresponding boolean functions. * These functions are passed the attribute and the current node's value of the attribute. * @property operators * @type object */ operators: { '': function(node, attr) { return Y.DOM.getAttribute(node, attr) !== ''; }, // Just test for existence of attribute '~=': '(?:^|\\s+){val}(?:\\s+|$)', // space-delimited '|=': '^{val}-?' // optional hyphen-delimited }, pseudos: { 'first-child': function(node) { return Y.DOM._children(node[PARENT_NODE])[0] === node; } }, _bruteQuery: function(selector, root, firstOnly) { var ret = [], nodes = [], tokens = Selector._tokenize(selector), token = tokens[tokens.length - 1], rootDoc = Y.DOM._getDoc(root), child, id, className, tagName; if (token) { // prefilter nodes id = token.id; className = token.className; tagName = token.tagName || '*'; if (root.getElementsByTagName) { // non-IE lacks DOM api on doc frags // try ID first, unless no root.all && root not in document // (root.all works off document, but not getElementById) if (id && (root.all || (root.nodeType === 9 || Y.DOM.inDoc(root)))) { nodes = Y.DOM.allById(id, root); // try className } else if (className) { nodes = root.getElementsByClassName(className); } else { // default to tagName nodes = root.getElementsByTagName(tagName); } } else { // brute getElementsByTagName() child = root.firstChild; while (child) { // only collect HTMLElements // match tag to supplement missing getElementsByTagName if (child.tagName && (tagName === '*' || child.tagName === tagName)) { nodes.push(child); } child = child.nextSibling || child.firstChild; } } if (nodes.length) { ret = Selector._filterNodes(nodes, tokens, firstOnly); } } return ret; }, _filterNodes: function(nodes, tokens, firstOnly) { var i = 0, j, len = tokens.length, n = len - 1, result = [], node = nodes[0], tmpNode = node, getters = Y.Selector.getters, operator, combinator, token, path, pass, value, tests, test; for (i = 0; (tmpNode = node = nodes[i++]);) { n = len - 1; path = null; testLoop: while (tmpNode && tmpNode.tagName) { token = tokens[n]; tests = token.tests; j = tests.length; if (j && !pass) { while ((test = tests[--j])) { operator = test[1]; if (getters[test[0]]) { value = getters[test[0]](tmpNode, test[0]); } else { value = tmpNode[test[0]]; if (test[0] === 'tagName' && !Selector._isXML) { value = value.toUpperCase(); } if (typeof value != 'string' && value !== undefined && value.toString) { value = value.toString(); // coerce for comparison } else if (value === undefined && tmpNode.getAttribute) { // use getAttribute for non-standard attributes value = tmpNode.getAttribute(test[0], 2); // 2 === force string for IE } } if ((operator === '=' && value !== test[2]) || // fast path for equality (typeof operator !== 'string' && // protect against String.test monkey-patch (Moo) operator.test && !operator.test(value)) || // regex test (!operator.test && // protect against RegExp as function (webkit) typeof operator === 'function' && !operator(tmpNode, test[0], test[2]))) { // function test // skip non element nodes or non-matching tags if ((tmpNode = tmpNode[path])) { while (tmpNode && (!tmpNode.tagName || (token.tagName && token.tagName !== tmpNode.tagName)) ) { tmpNode = tmpNode[path]; } } continue testLoop; } } } n--; // move to next token // now that we've passed the test, move up the tree by combinator if (!pass && (combinator = token.combinator)) { path = combinator.axis; tmpNode = tmpNode[path]; // skip non element nodes while (tmpNode && !tmpNode.tagName) { tmpNode = tmpNode[path]; } if (combinator.direct) { // one pass only path = null; } } else { // success if we made it this far result.push(node); if (firstOnly) { return result; } break; } } } node = tmpNode = null; return result; }, combinators: { ' ': { axis: 'parentNode' }, '>': { axis: 'parentNode', direct: true }, '+': { axis: 'previousSibling', direct: true } }, _parsers: [ { name: ATTRIBUTES, re: /^\uE003(-?[a-z]+[\w\-]*)+([~\|\^\$\*!=]=?)?['"]?([^\uE004'"]*)['"]?\uE004/i, fn: function(match, token) { var operator = match[2] || '', operators = Selector.operators, escVal = (match[3]) ? match[3].replace(/\\/g, '') : '', test; // add prefiltering for ID and CLASS if ((match[1] === 'id' && operator === '=') || (match[1] === 'className' && Y.config.doc.documentElement.getElementsByClassName && (operator === '~=' || operator === '='))) { token.prefilter = match[1]; match[3] = escVal; // escape all but ID for prefilter, which may run through QSA (via Dom.allById) token[match[1]] = (match[1] === 'id') ? match[3] : escVal; } // add tests if (operator in operators) { test = operators[operator]; if (typeof test === 'string') { match[3] = escVal.replace(Selector._reRegExpTokens, '\\$1'); test = new RegExp(test.replace('{val}', match[3])); } match[2] = test; } if (!token.last || token.prefilter !== match[1]) { return match.slice(1); } } }, { name: TAG_NAME, re: /^((?:-?[_a-z]+[\w-]*)|\*)/i, fn: function(match, token) { var tag = match[1]; if (!Selector._isXML) { tag = tag.toUpperCase(); } token.tagName = tag; if (tag !== '*' && (!token.last || token.prefilter)) { return [TAG_NAME, '=', tag]; } if (!token.prefilter) { token.prefilter = 'tagName'; } } }, { name: COMBINATOR, re: /^\s*([>+~]|\s)\s*/, fn: function(match, token) { } }, { name: PSEUDOS, re: /^:([\-\w]+)(?:\uE005['"]?([^\uE005]*)['"]?\uE006)*/i, fn: function(match, token) { var test = Selector[PSEUDOS][match[1]]; if (test) { // reorder match array and unescape special chars for tests if (match[2]) { match[2] = match[2].replace(/\\/g, ''); } return [match[2], test]; } else { // selector token not supported (possibly missing CSS3 module) return false; } } } ], _getToken: function(token) { return { tagName: null, id: null, className: null, attributes: {}, combinator: null, tests: [] }; }, /* Break selector into token units per simple selector. Combinator is attached to the previous token. */ _tokenize: function(selector) { selector = selector || ''; selector = Selector._parseSelector(Y.Lang.trim(selector)); var token = Selector._getToken(), // one token per simple selector (left selector holds combinator) query = selector, // original query for debug report tokens = [], // array of tokens found = false, // whether or not any matches were found this pass match, // the regex match test, i, parser; /* Search for selector patterns, store, and strip them from the selector string until no patterns match (invalid selector) or we run out of chars. Multiple attributes and pseudos are allowed, in any order. for example: 'form:first-child[type=button]:not(button)[lang|=en]' */ outer: do { found = false; // reset after full pass for (i = 0; (parser = Selector._parsers[i++]);) { if ( (match = parser.re.exec(selector)) ) { // note assignment if (parser.name !== COMBINATOR ) { token.selector = selector; } selector = selector.replace(match[0], ''); // strip current match from selector if (!selector.length) { token.last = true; } if (Selector._attrFilters[match[1]]) { // convert class to className, etc. match[1] = Selector._attrFilters[match[1]]; } test = parser.fn(match, token); if (test === false) { // selector not supported found = false; break outer; } else if (test) { token.tests.push(test); } if (!selector.length || parser.name === COMBINATOR) { tokens.push(token); token = Selector._getToken(token); if (parser.name === COMBINATOR) { token.combinator = Y.Selector.combinators[match[1]]; } } found = true; } } } while (found && selector.length); if (!found || selector.length) { // not fully parsed tokens = []; } return tokens; }, _replaceMarkers: function(selector) { selector = selector.replace(/\[/g, '\uE003'); selector = selector.replace(/\]/g, '\uE004'); selector = selector.replace(/\(/g, '\uE005'); selector = selector.replace(/\)/g, '\uE006'); return selector; }, _replaceShorthand: function(selector) { var shorthand = Y.Selector.shorthand, re; for (re in shorthand) { if (shorthand.hasOwnProperty(re)) { selector = selector.replace(new RegExp(re, 'gi'), shorthand[re]); } } return selector; }, _parseSelector: function(selector) { var replaced = Y.Selector._replaceSelector(selector), selector = replaced.selector; // replace shorthand (".foo, #bar") after pseudos and attrs // to avoid replacing unescaped chars selector = Y.Selector._replaceShorthand(selector); selector = Y.Selector._restore('attr', selector, replaced.attrs); selector = Y.Selector._restore('pseudo', selector, replaced.pseudos); // replace braces and parens before restoring escaped chars // to avoid replacing ecaped markers selector = Y.Selector._replaceMarkers(selector); selector = Y.Selector._restore('esc', selector, replaced.esc); return selector; }, _attrFilters: { 'class': 'className', 'for': 'htmlFor' }, getters: { href: function(node, attr) { return Y.DOM.getAttribute(node, attr); }, id: function(node, attr) { return Y.DOM.getId(node); } } }; Y.mix(Y.Selector, SelectorCSS2, true); Y.Selector.getters.src = Y.Selector.getters.rel = Y.Selector.getters.href; // IE wants class with native queries if (Y.Selector.useNative && Y.config.doc.querySelector) { Y.Selector.shorthand['\\.(-?[_a-z]+[-\\w]*)'] = '[class~=$1]'; } }, '@VERSION@', {"requires": ["selector-native"]}); YUI.add('selector-css3', function (Y, NAME) { /** * The selector css3 module provides support for css3 selectors. * @module dom * @submodule selector-css3 * @for Selector */ /* an+b = get every _a_th node starting at the _b_th 0n+b = no repeat ("0" and "n" may both be omitted (together) , e.g. "0n+1" or "1", not "0+1"), return only the _b_th element 1n+b = get every element starting from b ("1" may may be omitted, e.g. "1n+0" or "n+0" or "n") an+0 = get every _a_th element, "0" may be omitted */ Y.Selector._reNth = /^(?:([\-]?\d*)(n){1}|(odd|even)$)*([\-+]?\d*)$/; Y.Selector._getNth = function(node, expr, tag, reverse) { Y.Selector._reNth.test(expr); var a = parseInt(RegExp.$1, 10), // include every _a_ elements (zero means no repeat, just first _a_) n = RegExp.$2, // "n" oddeven = RegExp.$3, // "odd" or "even" b = parseInt(RegExp.$4, 10) || 0, // start scan from element _b_ result = [], siblings = Y.DOM._children(node.parentNode, tag), op; if (oddeven) { a = 2; // always every other op = '+'; n = 'n'; b = (oddeven === 'odd') ? 1 : 0; } else if ( isNaN(a) ) { a = (n) ? 1 : 0; // start from the first or no repeat } if (a === 0) { // just the first if (reverse) { b = siblings.length - b + 1; } if (siblings[b - 1] === node) { return true; } else { return false; } } else if (a < 0) { reverse = !!reverse; a = Math.abs(a); } if (!reverse) { for (var i = b - 1, len = siblings.length; i < len; i += a) { if ( i >= 0 && siblings[i] === node ) { return true; } } } else { for (var i = siblings.length - b, len = siblings.length; i >= 0; i -= a) { if ( i < len && siblings[i] === node ) { return true; } } } return false; }; Y.mix(Y.Selector.pseudos, { 'root': function(node) { return node === node.ownerDocument.documentElement; }, 'nth-child': function(node, expr) { return Y.Selector._getNth(node, expr); }, 'nth-last-child': function(node, expr) { return Y.Selector._getNth(node, expr, null, true); }, 'nth-of-type': function(node, expr) { return Y.Selector._getNth(node, expr, node.tagName); }, 'nth-last-of-type': function(node, expr) { return Y.Selector._getNth(node, expr, node.tagName, true); }, 'last-child': function(node) { var children = Y.DOM._children(node.parentNode); return children[children.length - 1] === node; }, 'first-of-type': function(node) { return Y.DOM._children(node.parentNode, node.tagName)[0] === node; }, 'last-of-type': function(node) { var children = Y.DOM._children(node.parentNode, node.tagName); return children[children.length - 1] === node; }, 'only-child': function(node) { var children = Y.DOM._children(node.parentNode); return children.length === 1 && children[0] === node; }, 'only-of-type': function(node) { var children = Y.DOM._children(node.parentNode, node.tagName); return children.length === 1 && children[0] === node; }, 'empty': function(node) { return node.childNodes.length === 0; }, 'not': function(node, expr) { return !Y.Selector.test(node, expr); }, 'contains': function(node, expr) { var text = node.innerText || node.textContent || ''; return text.indexOf(expr) > -1; }, 'checked': function(node) { return (node.checked === true || node.selected === true); }, enabled: function(node) { return (node.disabled !== undefined && !node.disabled); }, disabled: function(node) { return (node.disabled); } }); Y.mix(Y.Selector.operators, { '^=': '^{val}', // Match starts with value '$=': '{val}$', // Match ends with value '*=': '{val}' // Match contains value as substring }); Y.Selector.combinators['~'] = { axis: 'previousSibling' }; }, '@VERSION@', {"requires": ["selector-native", "selector-css2"]}); YUI.add('yui-log', function (Y, NAME) { /** * Provides console log capability and exposes a custom event for * console implementations. This module is a `core` YUI module, * <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-log */ var INSTANCE = Y, LOGEVENT = 'yui:log', UNDEFINED = 'undefined', LEVELS = { debug: 1, info: 2, warn: 4, error: 8 }; /** * If the 'debug' config is true, a 'yui:log' event will be * dispatched, which the Console widget and anything else * can consume. If the 'useBrowserConsole' config is true, it will * write to the browser console if available. YUI-specific log * messages will only be present in the -debug versions of the * JS files. The build system is supposed to remove log statements * from the raw and minified versions of the files. * * @method log * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.log = function(msg, cat, src, silent) { var bail, excl, incl, m, f, minlevel, Y = INSTANCE, c = Y.config, publisher = (Y.fire) ? Y : YUI.Env.globalEvents; // suppress log message if the config is off or the event stack // or the event call stack contains a consumer of the yui:log event if (c.debug) { // apply source filters src = src || ""; if (typeof src !== "undefined") { excl = c.logExclude; incl = c.logInclude; if (incl && !(src in incl)) { bail = 1; } else if (incl && (src in incl)) { bail = !incl[src]; } else if (excl && (src in excl)) { bail = excl[src]; } // Determine the current minlevel as defined in configuration Y.config.logLevel = Y.config.logLevel || 'debug'; minlevel = LEVELS[Y.config.logLevel.toLowerCase()]; if (cat in LEVELS && LEVELS[cat] < minlevel) { // Skip this message if the we don't meet the defined minlevel bail = 1; } } if (!bail) { if (c.useBrowserConsole) { m = (src) ? src + ': ' + msg : msg; if (Y.Lang.isFunction(c.logFn)) { c.logFn.call(Y, msg, cat, src); } else if (typeof console !== UNDEFINED && console.log) { f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log'; console[f](m); } else if (typeof opera !== UNDEFINED) { opera.postError(m); } } if (publisher && !silent) { if (publisher === Y && (!publisher.getEvent(LOGEVENT))) { publisher.publish(LOGEVENT, { broadcast: 2 }); } publisher.fire(LOGEVENT, { msg: msg, cat: cat, src: src }); } } } return Y; }; /** * Write a system message. This message will be preserved in the * minified and raw versions of the YUI files, unlike log statements. * @method message * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.message = function() { return INSTANCE.log.apply(INSTANCE, arguments); }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('dump', function (Y, NAME) { /** * Returns a simple string representation of the object or array. * Other types of objects will be returned unprocessed. Arrays * are expected to be indexed. Use object notation for * associative arrays. * * If included, the dump method is added to the YUI instance. * * @module dump */ var L = Y.Lang, OBJ = '{...}', FUN = 'f(){...}', COMMA = ', ', ARROW = ' => ', /** * Returns a simple string representation of the object or array. * Other types of objects will be returned unprocessed. Arrays * are expected to be indexed. * * @method dump * @param {Object} o The object to dump. * @param {Number} d How deep to recurse child objects, default 3. * @return {String} the dump result. * @for YUI */ dump = function(o, d) { var i, len, s = [], type = L.type(o); // Cast non-objects to string // Skip dates because the std toString is what we want // Skip HTMLElement-like objects because trying to dump // an element will cause an unhandled exception in FF 2.x if (!L.isObject(o)) { return o + ''; } else if (type == 'date') { return o; } else if (o.nodeType && o.tagName) { return o.tagName + '#' + o.id; } else if (o.document && o.navigator) { return 'window'; } else if (o.location && o.body) { return 'document'; } else if (type == 'function') { return FUN; } // dig into child objects the depth specifed. Default 3 d = (L.isNumber(d)) ? d : 3; // arrays [1, 2, 3] if (type == 'array') { s.push('['); for (i = 0, len = o.length; i < len; i = i + 1) { if (L.isObject(o[i])) { s.push((d > 0) ? L.dump(o[i], d - 1) : OBJ); } else { s.push(o[i]); } s.push(COMMA); } if (s.length > 1) { s.pop(); } s.push(']'); // regexp /foo/ } else if (type == 'regexp') { s.push(o.toString()); // objects {k1 => v1, k2 => v2} } else { s.push('{'); for (i in o) { if (o.hasOwnProperty(i)) { try { s.push(i + ARROW); if (L.isObject(o[i])) { s.push((d > 0) ? L.dump(o[i], d - 1) : OBJ); } else { s.push(o[i]); } s.push(COMMA); } catch (e) { s.push('Error: ' + e.message); } } } if (s.length > 1) { s.pop(); } s.push('}'); } return s.join(''); }; Y.dump = dump; L.dump = dump; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('transition-timer', function (Y, NAME) { /** * Provides the base Transition class, for animating numeric properties. * * @module transition * @submodule transition-timer */ var Transition = Y.Transition; Y.mix(Transition.prototype, { _start: function() { if (Transition.useNative) { this._runNative(); } else { this._runTimer(); } }, _runTimer: function() { var anim = this; anim._initAttrs(); Transition._running[Y.stamp(anim)] = anim; anim._startTime = new Date(); Transition._startTimer(); }, _endTimer: function() { var anim = this; delete Transition._running[Y.stamp(anim)]; anim._startTime = null; }, _runFrame: function() { var t = new Date() - this._startTime; this._runAttrs(t); }, _runAttrs: function(time) { var anim = this, node = anim._node, config = anim._config, uid = Y.stamp(node), attrs = Transition._nodeAttrs[uid], customAttr = Transition.behaviors, done = false, allDone = false, data, name, attribute, setter, elapsed, delay, d, t, i; for (name in attrs) { if ((attribute = attrs[name]) && attribute.transition === anim) { d = attribute.duration; delay = attribute.delay; elapsed = (time - delay) / 1000; t = time; data = { type: 'propertyEnd', propertyName: name, config: config, elapsedTime: elapsed }; setter = (i in customAttr && 'set' in customAttr[i]) ? customAttr[i].set : Transition.DEFAULT_SETTER; done = (t >= d); if (t > d) { t = d; } if (!delay || time >= delay) { setter(anim, name, attribute.from, attribute.to, t - delay, d - delay, attribute.easing, attribute.unit); if (done) { delete attrs[name]; anim._count--; if (config[name] && config[name].on && config[name].on.end) { config[name].on.end.call(Y.one(node), data); } //node.fire('transition:propertyEnd', data); if (!allDone && anim._count <= 0) { allDone = true; anim._end(elapsed); anim._endTimer(); } } } } } }, _initAttrs: function() { var anim = this, customAttr = Transition.behaviors, uid = Y.stamp(anim._node), attrs = Transition._nodeAttrs[uid], attribute, duration, delay, easing, val, name, mTo, mFrom, unit, begin, end; for (name in attrs) { if ((attribute = attrs[name]) && attribute.transition === anim) { duration = attribute.duration * 1000; delay = attribute.delay * 1000; easing = attribute.easing; val = attribute.value; // only allow supported properties if (name in anim._node.style || name in Y.DOM.CUSTOM_STYLES) { begin = (name in customAttr && 'get' in customAttr[name]) ? customAttr[name].get(anim, name) : Transition.DEFAULT_GETTER(anim, name); mFrom = Transition.RE_UNITS.exec(begin); mTo = Transition.RE_UNITS.exec(val); begin = mFrom ? mFrom[1] : begin; end = mTo ? mTo[1] : val; unit = mTo ? mTo[2] : mFrom ? mFrom[2] : ''; // one might be zero TODO: mixed units if (!unit && Transition.RE_DEFAULT_UNIT.test(name)) { unit = Transition.DEFAULT_UNIT; } if (typeof easing === 'string') { if (easing.indexOf('cubic-bezier') > -1) { easing = easing.substring(13, easing.length - 1).split(','); } else if (Transition.easings[easing]) { easing = Transition.easings[easing]; } } attribute.from = Number(begin); attribute.to = Number(end); attribute.unit = unit; attribute.easing = easing; attribute.duration = duration + delay; attribute.delay = delay; } else { delete attrs[name]; anim._count--; } } } }, destroy: function() { this.detachAll(); this._node = null; } }, true); Y.mix(Y.Transition, { _runtimeAttrs: {}, /* * Regex of properties that should use the default unit. * * @property RE_DEFAULT_UNIT * @static */ RE_DEFAULT_UNIT: /^width|height|top|right|bottom|left|margin.*|padding.*|border.*$/i, /* * The default unit to use with properties that pass the RE_DEFAULT_UNIT test. * * @property DEFAULT_UNIT * @static */ DEFAULT_UNIT: 'px', /* * Time in milliseconds passed to setInterval for frame processing * * @property intervalTime * @default 20 * @static */ intervalTime: 20, /* * Bucket for custom getters and setters * * @property behaviors * @static */ behaviors: { left: { get: function(anim, attr) { return Y.DOM._getAttrOffset(anim._node, attr); } } }, /* * The default setter to use when setting object properties. * * @property DEFAULT_SETTER * @static */ DEFAULT_SETTER: function(anim, att, from, to, elapsed, duration, fn, unit) { from = Number(from); to = Number(to); var node = anim._node, val = Transition.cubicBezier(fn, elapsed / duration); val = from + val[0] * (to - from); if (node) { if (att in node.style || att in Y.DOM.CUSTOM_STYLES) { unit = unit || ''; Y.DOM.setStyle(node, att, val + unit); } } else { anim._end(); } }, /* * The default getter to use when getting object properties. * * @property DEFAULT_GETTER * @static */ DEFAULT_GETTER: function(anim, att) { var node = anim._node, val = ''; if (att in node.style || att in Y.DOM.CUSTOM_STYLES) { val = Y.DOM.getComputedStyle(node, att); } return val; }, _startTimer: function() { if (!Transition._timer) { Transition._timer = setInterval(Transition._runFrame, Transition.intervalTime); } }, _stopTimer: function() { clearInterval(Transition._timer); Transition._timer = null; }, /* * Called per Interval to handle each animation frame. * @method _runFrame * @private * @static */ _runFrame: function() { var done = true, anim; for (anim in Transition._running) { if (Transition._running[anim]._runFrame) { done = false; Transition._running[anim]._runFrame(); } } if (done) { Transition._stopTimer(); } }, cubicBezier: function(p, t) { var x0 = 0, y0 = 0, x1 = p[0], y1 = p[1], x2 = p[2], y2 = p[3], x3 = 1, y3 = 0, A = x3 - 3 * x2 + 3 * x1 - x0, B = 3 * x2 - 6 * x1 + 3 * x0, C = 3 * x1 - 3 * x0, D = x0, E = y3 - 3 * y2 + 3 * y1 - y0, F = 3 * y2 - 6 * y1 + 3 * y0, G = 3 * y1 - 3 * y0, H = y0, x = (((A*t) + B)*t + C)*t + D, y = (((E*t) + F)*t + G)*t + H; return [x, y]; }, easings: { ease: [0.25, 0, 1, 0.25], linear: [0, 0, 1, 1], 'ease-in': [0.42, 0, 1, 1], 'ease-out': [0, 0, 0.58, 1], 'ease-in-out': [0.42, 0, 0.58, 1] }, _running: {}, _timer: null, RE_UNITS: /^(-?\d*\.?\d*){1}(em|ex|px|in|cm|mm|pt|pc|%)*$/ }, true); Transition.behaviors.top = Transition.behaviors.bottom = Transition.behaviors.right = Transition.behaviors.left; Y.Transition = Transition; }, '@VERSION@', {"requires": ["transition"]}); YUI.add('yui', function (Y, NAME) { // empty }, '@VERSION@', { "use": [ "yui", "oop", "dom", "event-custom-base", "event-base", "pluginhost", "node", "event-delegate", "io-base", "json-parse", "transition", "selector-css3", "dom-style-ie", "querystring-stringify-simple" ] }); var Y = YUI().use('*');
assets/js/pages/about.js
dotcypress/eon
import React from 'react'; import { Jumbotron } from 'react-bootstrap'; export class AboutPage extends React.Component { constructor() { super(); }; render() { return <Jumbotron> <h1>eon</h1> <p>React+Flux+Babel+Koa+Bootstrap+Webpack boilerplate.</p> </Jumbotron>; }; }
node_modules/node-captcha/node_modules/canvas/node_modules/mocha/node_modules/jade/node_modules/markdown/node_modules/nopt/node_modules/abbrev/node_modules/tap/node_modules/signal-exit/node_modules/standard/node_modules/eslint/lib/eslint.js
wenjoy/homePage
/** * @fileoverview Main ESLint object. * @author Nicholas C. Zakas */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ var estraverse = require("estraverse-fb"), escope = require("escope"), environments = require("../conf/environments"), assign = require("object-assign"), rules = require("./rules"), util = require("./util"), RuleContext = require("./rule-context"), timing = require("./timing"), createTokenStore = require("./token-store.js"), EventEmitter = require("events").EventEmitter, escapeRegExp = require("escape-string-regexp"); //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ // TODO: Remove when estraverse is updated estraverse.Syntax.Super = "Super"; estraverse.VisitorKeys.Super = []; /** * Parses a list of "name:boolean_value" or/and "name" options divided by comma or * whitespace. * @param {string} string The string to parse. * @returns {Object} Result map object of names and boolean values */ function parseBooleanConfig(string) { var items = {}; // Collapse whitespace around : to make parsing easier string = string.replace(/\s*:\s*/g, ":"); // Collapse whitespace around , string = string.replace(/\s*,\s*/g, ","); string.split(/\s|,+/).forEach(function(name) { if (!name) { return; } var pos = name.indexOf(":"), value; if (pos !== -1) { value = name.substring(pos + 1, name.length); name = name.substring(0, pos); } items[name] = (value === "true"); }); return items; } /** * Parses a JSON-like config. * @param {string} string The string to parse. * @param {Object} location Start line and column of comments for potential error message. * @param {Object[]} messages The messages queue for potential error message. * @returns {Object} Result map object */ function parseJsonConfig(string, location, messages) { var items = {}; string = string.replace(/([a-zA-Z0-9\-\/]+):/g, "\"$1\":").replace(/(\]|[0-9])\s+(?=")/, "$1,"); try { items = JSON.parse("{" + string + "}"); } catch(ex) { messages.push({ fatal: true, severity: 2, message: "Failed to parse JSON from '" + string + "': " + ex.message, line: location.start.line, column: location.start.column }); } return items; } /** * Parses a config of values separated by comma. * @param {string} string The string to parse. * @returns {Object} Result map of values and true values */ function parseListConfig(string) { var items = {}; // Collapse whitespace around , string = string.replace(/\s*,\s*/g, ","); string.split(/,+/).forEach(function(name) { name = name.trim(); if (!name) { return; } items[name] = true; }); return items; } /** * @param {Scope} scope The scope object to check. * @param {string} name The name of the variable to look up. * @returns {Variable} The variable object if found or null if not. */ function getVariable(scope, name) { var variable = null; scope.variables.some(function(v) { if (v.name === name) { variable = v; return true; } else { return false; } }); return variable; } /** * Ensures that variables representing built-in properties of the Global Object, * and any globals declared by special block comments, are present in the global * scope. * @param {ASTNode} program The top node of the AST. * @param {Scope} globalScope The global scope. * @param {Object} config The existing configuration data. * @returns {void} */ function addDeclaredGlobals(program, globalScope, config) { var declaredGlobals = {}, explicitGlobals = {}, builtin = environments.builtin; assign(declaredGlobals, builtin); Object.keys(config.env).forEach(function (name) { if (config.env[name]) { var environmentGlobals = environments[name] && environments[name].globals; if (environmentGlobals) { assign(declaredGlobals, environmentGlobals); } } }); assign(declaredGlobals, config.globals); assign(explicitGlobals, config.astGlobals); Object.keys(declaredGlobals).forEach(function(name) { var variable = getVariable(globalScope, name); if (!variable) { variable = new escope.Variable(name, globalScope); variable.eslintExplicitGlobal = false; globalScope.variables.push(variable); } variable.writeable = declaredGlobals[name]; }); Object.keys(explicitGlobals).forEach(function(name) { var variable = getVariable(globalScope, name); if (!variable) { variable = new escope.Variable(name, globalScope); variable.eslintExplicitGlobal = true; globalScope.variables.push(variable); } variable.writeable = explicitGlobals[name]; }); } /** * Add data to reporting configuration to disable reporting for list of rules * starting from start location * @param {Object[]} reportingConfig Current reporting configuration * @param {Object} start Position to start * @param {string[]} rulesToDisable List of rules * @returns {void} */ function disableReporting(reportingConfig, start, rulesToDisable) { if (rulesToDisable.length) { rulesToDisable.forEach(function(rule) { reportingConfig.push({ start: start, end: null, rule: rule }); }); } else { reportingConfig.push({ start: start, end: null, rule: null }); } } /** * Add data to reporting configuration to enable reporting for list of rules * starting from start location * @param {Object[]} reportingConfig Current reporting configuration * @param {Object} start Position to start * @param {string[]} rulesToEnable List of rules * @returns {void} */ function enableReporting(reportingConfig, start, rulesToEnable) { var i; if (rulesToEnable.length) { rulesToEnable.forEach(function(rule) { for (i = reportingConfig.length - 1; i >= 0; i--) { if (!reportingConfig[i].end && reportingConfig[i].rule === rule ) { reportingConfig[i].end = start; break; } } }); } else { // find all previous disabled locations if they was started as list of rules var prevStart; for (i = reportingConfig.length - 1; i >= 0; i--) { if (prevStart && prevStart !== reportingConfig[i].start) { break; } if (!reportingConfig[i].end) { reportingConfig[i].end = start; prevStart = reportingConfig[i].start; } } } } /** * Parses comments in file to extract file-specific config of rules, globals * and environments and merges them with global config; also code blocks * where reporting is disabled or enabled and merges them with reporting config. * @param {ASTNode} ast The top node of the AST. * @param {Object} config The existing configuration data. * @param {Object[]} reportingConfig The existing reporting configuration data. * @param {Object[]} messages The messages queue. * @returns {void} */ function modifyConfigsFromComments(ast, config, reportingConfig, messages) { var commentConfig = { astGlobals: {}, rules: {}, env: {} }; var commentRules = {}; ast.comments.forEach(function(comment) { var value = comment.value.trim(); var match = /^(eslint-\w+|eslint-\w+-\w+|eslint|globals?)(\s|$)/.exec(value); if (match) { value = value.substring(match.index + match[1].length); if (comment.type === "Block") { switch (match[1]) { case "globals": case "global": assign(commentConfig.astGlobals, parseBooleanConfig(value)); break; case "eslint-env": assign(commentConfig.env, parseListConfig(value)); break; case "eslint-disable": disableReporting(reportingConfig, comment.loc.start, Object.keys(parseListConfig(value))); break; case "eslint-enable": enableReporting(reportingConfig, comment.loc.start, Object.keys(parseListConfig(value))); break; case "eslint": var items = parseJsonConfig(value, comment.loc, messages); Object.keys(items).forEach(function(name) { var ruleValue = items[name]; if (typeof ruleValue === "number" || (Array.isArray(ruleValue) && typeof ruleValue[0] === "number")) { commentRules[name] = ruleValue; } }); break; // no default } } else { // comment.type === "Line" if (match[1] === "eslint-disable-line") { disableReporting(reportingConfig, { "line": comment.loc.start.line, "column": 0 }, Object.keys(parseListConfig(value))); enableReporting(reportingConfig, comment.loc.end, Object.keys(parseListConfig(value))); } } } }); // apply environment configs Object.keys(commentConfig.env).forEach(function (name) { if (environments[name]) { util.mergeConfigs(commentConfig, environments[name]); } }); assign(commentConfig.rules, commentRules); util.mergeConfigs(config, commentConfig); } /** * Check if message of rule with ruleId should be ignored in location * @param {Object[]} reportingConfig Collection of ignore records * @param {string} ruleId Id of rule * @param {Object} location Location of message * @returns {boolean} True if message should be ignored, false otherwise */ function isDisabledByReportingConfig(reportingConfig, ruleId, location) { for (var i = 0, c = reportingConfig.length; i < c; i++) { var ignore = reportingConfig[i]; if ((!ignore.rule || ignore.rule === ruleId) && (location.line > ignore.start.line || (location.line === ignore.start.line && location.column >= ignore.start.column)) && (!ignore.end || (location.line < ignore.end.line || (location.line === ignore.end.line && location.column <= ignore.end.column)))) { return true; } } return false; } /** * Process initial config to make it safe to extend by file comment config * @param {Object} config Initial config * @returns {Object} Processed config */ function prepareConfig(config) { config.globals = config.globals || config.global || {}; delete config.global; var copiedRules = {}, ecmaFeatures = {}, preparedConfig; if (typeof config.rules === "object") { Object.keys(config.rules).forEach(function(k) { var rule = config.rules[k]; if (rule === null) { throw new Error("Invalid config for rule '" + k + "'\."); } if (Array.isArray(rule)) { copiedRules[k] = rule.slice(); } else { copiedRules[k] = rule; } }); } // merge in environment ecmaFeatures if (typeof config.env === "object") { Object.keys(config.env).forEach(function(env) { if (config.env[env] && environments[env].ecmaFeatures) { assign(ecmaFeatures, environments[env].ecmaFeatures); } }); } preparedConfig = { rules: copiedRules, parser: config.parser || "espree", globals: util.mergeConfigs({}, config.globals), env: util.mergeConfigs({}, config.env || {}), settings: util.mergeConfigs({}, config.settings || {}), ecmaFeatures: util.mergeConfigs(ecmaFeatures, config.ecmaFeatures || {}) }; // can't have global return inside of modules if (preparedConfig.ecmaFeatures.modules) { preparedConfig.ecmaFeatures.globalReturn = false; } return preparedConfig; } //------------------------------------------------------------------------------ // Public Interface //------------------------------------------------------------------------------ /** * Object that is responsible for verifying JavaScript text * @name eslint */ module.exports = (function() { var api = Object.create(new EventEmitter()), messages = [], currentText = null, currentTextLines = [], currentConfig = null, currentTokens = null, currentScopes = null, scopeMap = null, scopeManager = null, currentFilename = null, controller = null, reportingConfig = [], commentLocsEnter = [], commentLocsExit = [], currentAST = null; /** * Parses text into an AST. Moved out here because the try-catch prevents * optimization of functions, so it's best to keep the try-catch as isolated * as possible * @param {string} text The text to parse. * @param {Object} config The ESLint configuration object. * @returns {ASTNode} The AST if successful or null if not. * @private */ function parse(text, config) { var parser; try { parser = require(config.parser); } catch (ex) { messages.push({ fatal: true, severity: 2, message: ex.message, line: 0, column: 0 }); return null; } /* * Check for parsing errors first. If there's a parsing error, nothing * else can happen. However, a parsing error does not throw an error * from this method - it's just considered a fatal error message, a * problem that ESLint identified just like any other. */ try { return parser.parse(text, { loc: true, range: true, raw: true, tokens: true, comment: true, attachComment: true, ecmaFeatures: config.ecmaFeatures }); } catch (ex) { messages.push({ fatal: true, severity: 2, // messages come as "Line X: Unexpected token foo", so strip off leading part message: ex.message.substring(ex.message.indexOf(":") + 1).trim(), line: ex.lineNumber, column: ex.column }); return null; } } /** * Check collection of comments to prevent double event for comment as * leading and trailing, then emit event if passing * @param {ASTNode[]} comments Collection of comment nodes * @param {Object[]} locs List of locations of previous comment nodes * @param {string} eventName Event name postfix * @returns {void} */ function emitComments(comments, locs, eventName) { if (comments.length) { comments.forEach(function(node) { if (locs.indexOf(node.loc) >= 0) { locs.splice(locs.indexOf(node.loc), 1); } else { locs.push(node.loc); api.emit(node.type + eventName, node); } }); } } /** * Shortcut to check and emit enter of comment nodes * @param {ASTNode[]} comments Collection of comment nodes * @returns {void} */ function emitCommentsEnter(comments) { emitComments(comments, commentLocsEnter, "Comment"); } /** * Shortcut to check and emit exit of comment nodes * @param {ASTNode[]} comments Collection of comment nodes * @returns {void} */ function emitCommentsExit(comments) { emitComments(comments, commentLocsExit, "Comment:exit"); } /** * Get the severity level of a rule (0 - none, 1 - warning, 2 - error) * Returns 0 if the rule config is not valid (an Array or a number) * @param {Array|number} ruleConfig rule configuration * @returns {number} 0, 1, or 2, indicating rule severity */ function getRuleSeverity(ruleConfig) { if (typeof ruleConfig === "number") { return ruleConfig; } else if (Array.isArray(ruleConfig)) { return ruleConfig[0]; } else { return 0; } } /** * Get the options for a rule (not including severity), if any * @param {Array|number} ruleConfig rule configuration * @returns {Array} of rule options, empty Array if none */ function getRuleOptions(ruleConfig) { if (Array.isArray(ruleConfig)) { return ruleConfig.slice(1); } else { return []; } } // set unlimited listeners (see https://github.com/eslint/eslint/issues/524) api.setMaxListeners(0); /** * Resets the internal state of the object. * @returns {void} */ api.reset = function() { this.removeAllListeners(); messages = []; currentAST = null; currentConfig = null; currentText = null; currentTextLines = []; currentTokens = null; currentScopes = null; scopeMap = null; scopeManager = null; controller = null; reportingConfig = []; commentLocsEnter = []; commentLocsExit = []; }; /** * Verifies the text against the rules specified by the second argument. * @param {string} text The JavaScript text to verify. * @param {Object} config An object whose keys specify the rules to use. * @param {string=} filename The optional filename of the file being checked. * If this is not set, the filename will default to '<input>' in the rule context. * @param {boolean=} saveState Indicates if the state from the last run should be saved. * Mostly useful for testing purposes. * @returns {Object[]} The results as an array of messages or null if no messages. */ api.verify = function(text, config, filename, saveState) { var ast, shebang, ecmaFeatures, ecmaVersion; // set the current parsed filename currentFilename = filename; if (!saveState) { this.reset(); } // there's no input, just exit here if (text.trim().length === 0) { currentText = text; return messages; } // process initial config to make it safe to extend config = prepareConfig(config || {}); ast = parse(text.replace(/^#!([^\r\n]+)/, function(match, captured) { shebang = captured; return "//" + captured; }), config); // if espree failed to parse the file, there's no sense in setting up rules if (ast) { currentAST = ast; // parse global comments and modify config modifyConfigsFromComments(ast, config, reportingConfig, messages); // enable appropriate rules Object.keys(config.rules).filter(function(key) { return getRuleSeverity(config.rules[key]) > 0; }).forEach(function(key) { var ruleCreator = rules.get(key), severity = getRuleSeverity(config.rules[key]), options = getRuleOptions(config.rules[key]), rule; if (ruleCreator) { try { rule = ruleCreator(new RuleContext( key, api, severity, options, config.settings, config.ecmaFeatures )); // add all the node types as listeners Object.keys(rule).forEach(function(nodeType) { api.on(nodeType, timing.enabled ? timing.time(key, rule[nodeType]) : rule[nodeType] ); }); } catch(ex) { ex.message = "Error while loading rule '" + key + "': " + ex.message; throw ex; } } else { throw new Error("Definition for rule '" + key + "' was not found."); } }); // save config so rules can access as necessary currentConfig = config; currentText = text; controller = new estraverse.Controller(); ecmaFeatures = currentConfig.ecmaFeatures; ecmaVersion = (ecmaFeatures.blockBindings || ecmaFeatures.classes || ecmaFeatures.modules || ecmaFeatures.defaultParams || ecmaFeatures.destructuring) ? 6 : 5; // gather data that may be needed by the rules scopeManager = escope.analyze(ast, { ignoreEval: true, nodejsScope: ecmaFeatures.globalReturn, ecmaVersion: ecmaVersion, sourceType: ecmaFeatures.modules ? "module" : "script" }); currentScopes = scopeManager.scopes; /* * Index the scopes by the start range of their block for efficient * lookup in getScope. */ scopeMap = []; currentScopes.forEach(function (scope, index) { var range = scope.block.range[0]; // Sometimes two scopes are returned for a given node. This is // handled later in a known way, so just don't overwrite here. if (!scopeMap[range]) { scopeMap[range] = index; } }); /* * Split text here into array of lines so * it's not being done repeatedly * by individual rules. */ currentTextLines = currentText.split(/\r\n|\r|\n|\u2028|\u2029/g); // Freezing so array isn't accidentally changed by a rule. Object.freeze(currentTextLines); currentTokens = createTokenStore(ast.tokens); Object.keys(currentTokens).forEach(function(method) { api[method] = currentTokens[method]; }); // augment global scope with declared global variables addDeclaredGlobals(ast, currentScopes[0], currentConfig); // remove shebang comments if (shebang && ast.comments.length && ast.comments[0].value === shebang) { ast.comments.splice(0, 1); if (ast.body.length && ast.body[0].leadingComments && ast.body[0].leadingComments[0].value === shebang) { ast.body[0].leadingComments.splice(0, 1); } } /* * Each node has a type property. Whenever a particular type of node is found, * an event is fired. This allows any listeners to automatically be informed * that this type of node has been found and react accordingly. */ controller.traverse(ast, { enter: function(node, parent) { var comments = api.getComments(node); emitCommentsEnter(comments.leading); node.parent = parent; api.emit(node.type, node); emitCommentsEnter(comments.trailing); }, leave: function(node) { var comments = api.getComments(node); emitCommentsExit(comments.trailing); api.emit(node.type + ":exit", node); emitCommentsExit(comments.leading); } }); } // sort by line and column messages.sort(function(a, b) { var lineDiff = a.line - b.line; if (lineDiff === 0) { return a.column - b.column; } else { return lineDiff; } }); return messages; }; /** * Reports a message from one of the rules. * @param {string} ruleId The ID of the rule causing the message. * @param {number} severity The severity level of the rule as configured. * @param {ASTNode} node The AST node that the message relates to. * @param {Object=} location An object containing the error line and column * numbers. If location is not provided the node's start location will * be used. * @param {string} message The actual message. * @param {Object} opts Optional template data which produces a formatted message * with symbols being replaced by this object's values. * @returns {void} */ api.report = function(ruleId, severity, node, location, message, opts) { if (typeof location === "string") { opts = message; message = location; location = node.loc.start; } Object.keys(opts || {}).forEach(function (key) { var rx = new RegExp("{{" + escapeRegExp(key) + "}}", "g"); message = message.replace(rx, opts[key]); }); if (isDisabledByReportingConfig(reportingConfig, ruleId, location)) { return; } messages.push({ ruleId: ruleId, severity: severity, message: message, line: location.line, column: location.column, nodeType: node.type, source: currentTextLines[location.line - 1] || "" }); }; /** * Gets the source code for the given node. * @param {ASTNode=} node The AST node to get the text for. * @param {int=} beforeCount The number of characters before the node to retrieve. * @param {int=} afterCount The number of characters after the node to retrieve. * @returns {string} The text representing the AST node. */ api.getSource = function(node, beforeCount, afterCount) { if (node) { return (currentText !== null) ? currentText.slice(Math.max(node.range[0] - (beforeCount || 0), 0), node.range[1] + (afterCount || 0)) : null; } else { return currentText; } }; /** * Gets the entire source text split into an array of lines. * @returns {Array} The source text as an array of lines. */ api.getSourceLines = function() { return currentTextLines; }; /** * Retrieves an array containing all comments in the source code. * @returns {ASTNode[]} An array of comment nodes. */ api.getAllComments = function() { return currentAST.comments; }; /** * Gets all comments for the given node. * @param {ASTNode} node The AST node to get the comments for. * @returns {Object} The list of comments indexed by their position. */ api.getComments = function(node) { var leadingComments = node.leadingComments || [], trailingComments = node.trailingComments || []; /* * espree adds a "comments" array on Program nodes rather than * leadingComments/trailingComments. Comments are only left in the * Program node comments array if there is no executable code. */ if (node.type === "Program") { if (node.body.length === 0) { leadingComments = node.comments; } } return { leading: leadingComments, trailing: trailingComments }; }; /** * Retrieves the JSDoc comment for a given node. * @param {ASTNode} node The AST node to get the comment for. * @returns {ASTNode} The BlockComment node containing the JSDoc for the * given node or null if not found. */ api.getJSDocComment = function(node) { var parent = node.parent, line = node.loc.start.line; /** * Finds a JSDoc comment node in an array of comment nodes. * @param {ASTNode[]} comments The array of comment nodes to search. * @returns {ASTNode} The node if found, null if not. * @private */ function findJSDocComment(comments) { if (comments) { for (var i = comments.length - 1; i >= 0; i--) { if (comments[i].type === "Block" && comments[i].value.charAt(0) === "*") { if (line - comments[i].loc.end.line <= 1) { return comments[i]; } else { break; } } } } return null; } /** * Check to see if its a ES6 export declaration * @param {ASTNode} astNode - any node * @returns {boolean} whether the given node represents a export declaration */ function looksLikeExport(astNode) { return astNode.type === "ExportDefaultDeclaration" || astNode.type === "ExportNamedDeclaration" || astNode.type === "ExportAllDeclaration" || astNode.type === "ExportSpecifier"; } switch (node.type) { case "FunctionDeclaration": if (looksLikeExport(parent)) { return findJSDocComment(parent.leadingComments); } else { return findJSDocComment(node.leadingComments); } break; case "ArrowFunctionExpression": case "FunctionExpression": if (parent.type !== "CallExpression" || parent.callee !== node) { while (parent && !parent.leadingComments && !/Function/.test(parent.type)) { parent = parent.parent; } return parent && (parent.type !== "FunctionDeclaration") ? findJSDocComment(parent.leadingComments) : null; } // falls through default: return null; } }; /** * Gets nodes that are ancestors of current node. * @returns {ASTNode[]} Array of objects representing ancestors. */ api.getAncestors = function() { return controller.parents(); }; /** * Gets the deepest node containing a range index. * @param {int} index Range index of the desired node. * @returns {ASTNode} [description] */ api.getNodeByRangeIndex = function(index) { var result = null; estraverse.traverse(controller.root, { enter: function (node) { if (node.range[0] <= index && index < node.range[1]) { result = node; } else { this.skip(); } }, leave: function (node) { if (node === result) { this.break(); } } }); return result; }; /** * Gets the scope for the current node. * @returns {Object} An object representing the current node's scope. */ api.getScope = function() { var parents = controller.parents(), scope = currentScopes[0]; // Don't do this for Program nodes - they have no parents if (parents.length) { // if current node is function declaration, add it to the list var current = controller.current(); if (["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression", "SwitchStatement"].indexOf(current.type) >= 0) { parents.push(current); } // Ascend the current node's parents for (var i = parents.length - 1; i >= 0; --i) { scope = scopeManager.acquire(parents[i]); if (scope) { if (scope.type === "function-expression-name") { return scope.childScopes[0]; } else { return scope; } } } } return currentScopes[0]; }; /** * Record that a particular variable has been used in code * @param {string} name The name of the variable to mark as used * @returns {boolean} True if the variable was found and marked as used, * false if not. */ api.markVariableAsUsed = function(name) { var scope = this.getScope(), specialScope = currentConfig.ecmaFeatures.globalReturn || currentConfig.ecmaFeatures.modules, variables, i, len; // Special Node.js scope means we need to start one level deeper if (scope.type === "global" && specialScope) { scope = scope.childScopes[0]; } do { variables = scope.variables; for (i = 0, len = variables.length; i < len; i++) { if (variables[i].name === name) { variables[i].eslintUsed = true; return true; } } } while ( (scope = scope.upper) ); return false; }; /** * Gets the filename for the currently parsed source. * @returns {string} The filename associated with the source being parsed. * Defaults to "<input>" if no filename info is present. */ api.getFilename = function() { if (typeof currentFilename === "string") { return currentFilename; } else { return "<input>"; } }; /** * Defines a new linting rule. * @param {string} ruleId A unique rule identifier * @param {Function} ruleModule Function from context to object mapping AST node types to event handlers * @returns {void} */ var defineRule = api.defineRule = function(ruleId, ruleModule) { rules.define(ruleId, ruleModule); }; /** * Defines many new linting rules. * @param {object} rulesToDefine map from unique rule identifier to rule * @returns {void} */ api.defineRules = function(rulesToDefine) { Object.getOwnPropertyNames(rulesToDefine).forEach(function(ruleId) { defineRule(ruleId, rulesToDefine[ruleId]); }); }; /** * Gets the default eslint configuration. * @returns {Object} Object mapping rule IDs to their default configurations */ api.defaults = function() { return require("../conf/eslint.json"); }; return api; }());
src/JamiiWorld.js
sq0032/jamii-world
import React, { Component } from 'react'; import $ from 'jquery'; import {Motion, spring} from 'react-motion'; import MeetingRoom from './MeetingRoom'; import MeetingRoomView from './MeetingRoomView'; import Member from './Member'; export default class JamiiWorld extends Component { constructor(props){ super(props); this.state = { member_position: {x:100, y:100}, is_in_meetingroom: false }; } componentDidMount(){ $(window) .on('MOVE_TO_MEETINGROOM', {this:this}, this.on_moveToMeetingRoom) .on('MOVE_TO_LOBBY', {this:this}, this.on_moveToLobby); //Initial file fetch (passing in root id) } componentWillUnmount(){ $(window) .off('MOVE_TO_MEETINGROOM', this.on_moveToMeetingRoom) .off('MOVE_TO_LOBBY', this.on_moveToLobby); } on_moveToMeetingRoom(event) { const that = event.data.this; const pos = { x: 50, y: 50 }; that.setState({ member_position: pos, is_in_meetingroom:true }); } on_moveToLobby(event) { const that = event.data.this; that.setState({is_in_meetingroom:false}); } moveTo(event) { var dim = event.target.getBoundingClientRect(); const pos = { x: event.clientX - dim.left, y: event.clientY - dim.top }; this.setState({ member_position: pos, is_in_meetingroom: false }); } render() { const meetingRoomView = this.state.is_in_meetingroom ? (<MeetingRoomView />) : null console.log(meetingRoomView); return ( <div style={style.JamiiWorld}> <svg width="100%" height="100%" style={style.JamiiWorldSvg} onClick={this.moveTo.bind(this)} > <MeetingRoom pos={{x:5, y:5}}/> <Motion style={{x: spring(this.state.member_position.x), y:spring(this.state.member_position.y)}}> {pos => <Member pos={pos}/>} </Motion> </svg> {meetingRoomView} </div> ); } } const style = { JamiiWorld: { // position: "relative", // width: "100%", // height: "100%", position: "absolute", top: "10", bottom: "10", left: "10", right: "10", border: "5px solid black", }, JamiiWorldSvg: { // position: "absolute", // height: "100%", // top: "50", // bottom: "40", // left: "0", // right: "0", // width: "500px", // border: "5px solid black" } };
test/helpers/shallowRenderHelper.js
zhl666/gallery-by-react
/** * Function to get the shallow output for a given component * As we are using phantom.js, we also need to include the fn.proto.bind shim! * * @see http://simonsmith.io/unit-testing-react-components-without-a-dom/ * @author somonsmith */ import React from 'react'; import TestUtils from 'react-addons-test-utils'; /** * Get the shallow rendered component * * @param {Object} component The component to return the output for * @param {Object} props [optional] The components properties * @param {Mixed} ...children [optional] List of children * @return {Object} Shallow rendered output */ export default function createComponent(component, props = {}, ...children) { const shallowRenderer = TestUtils.createRenderer(); shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0])); return shallowRenderer.getRenderOutput(); }
packages/wix-style-react/src/ColorPicker/ColorPickerConverterHsb.js
wix/wix-style-react
import React from 'react'; import PropTypes from 'prop-types'; import Input from '../Input'; import { classes } from './ColorPickerConverter.st.css'; import ColorPickerConverterViewer from './ColorPickerConverterViewer'; import { safeColor, getHsbOrEmpty } from './utils'; export default class ColorPickerConverterHsb extends React.PureComponent { static propTypes = { dataHook: PropTypes.string, current: PropTypes.object.isRequired, onChange: PropTypes.func.isRequired, onAdd: PropTypes.func, }; state = getHsbOrEmpty(this.props.current); isInputsEmpty() { const { h, s, l } = this.state; return [h, s, l].every(value => value === ''); } render() { const { dataHook } = this.props; return ( <div className={classes.root} data-hook={dataHook}> <div className={classes.distribute}> <Input size="small" value={this.state.h} onChange={e => this.change('h', e)} placeholder={'H'} className={classes.distributedItem} /> <Input size="small" value={this.state.s} onChange={e => this.change('s', e)} placeholder={'S'} className={classes.distributedItem} /> <Input size="small" value={this.state.l} onChange={e => this.change('l', e)} placeholder={'B'} className={classes.distributedItem} /> </div> <ColorPickerConverterViewer {...this.props} color={this.props.current} /> </div> ); } UNSAFE_componentWillReceiveProps(props) { this.setState(getHsbOrEmpty(props.current)); } change(part, { target: { value } }) { this.setState({ [part]: value }, () => { const { h, s, l } = this.state; const isMissingData = [h, s, l].some(_value => _value === ''); const _color = safeColor( isMissingData && this.props.allowEmpty ? '' : this.state, this.props.allowEmpty, ); if (!isMissingData || this.isInputsEmpty()) { this.props.onChange(_color); } }); } }
packages/react-error-overlay/src/components/Footer.js
GreenGremlin/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import React from 'react'; import { darkGray } from '../styles'; const footerStyle = { fontFamily: 'sans-serif', color: darkGray, marginTop: '0.5rem', flex: '0 0 auto', }; type FooterPropsType = {| line1: string, line2?: string, |}; function Footer(props: FooterPropsType) { return ( <div style={footerStyle}> {props.line1} <br /> {props.line2} </div> ); } export default Footer;